无法将JTextField输入转换为Integer以获取输出中的总和

时间:2018-09-01 07:28:45

标签: java swing

我想计算JTextField上输入的总和。我认为我无法将输入转换为Integer。有什么建议吗?请在下面查看我的代码。提前感谢您,谢谢!

{
JPanel myPanel = new JPanel();   
JTextField SGEAC1 = new JTextField("0",10);
String sgeac1tx = SGEAC1.getText();
int eac1sg = Integer.parseInt(sgeac1tx);

JTextField SGEAC2 = new JTextField("0",10);
String sgeac2tx = SGEAC2.getText();
int eac2sg = Integer.parseInt(sgeac2tx);

myPanel.add(new JLabel("SG-EAC1:"));
myPanel.add(SGEAC1);
myPanel.add(Box.createHorizontalStrut(15));

myPanel.add(new JLabel("SG-EAC2:"));
myPanel.add(SGEAC2);
myPanel.add(Box.createHorizontalStrut(15));
int IPLBW = JOptionPane.showConfirmDialog(null, myPanel, "BW", 
JOptionPane.OK_CANCEL_OPTION);
int sumbw = eac1sg+eac2sg; }

 if (IPLBW == JOptionPane.OK_OPTION) {
 JTextArea ta = new JTextArea(100, 100);
   ta.setText("INTERNATIONAL UPSTREAM LINK UPDATE"+"\n" + sumbw 
     + "\n"+"-----------------------------"
     + "\n"+"TOTALS SG BW:   "+ sumbw +"/"
     + "\n"+"-----------------------------"
     + "\n" + "SG via EAC1"+"            " + SGEAC1.getText()+"G"
     + "\n" + "SG via EAC2"+"            " + SGEAC2.getText()+"G");

  JOptionPane.showMessageDialog(null, new JScrollPane(ta), "RESULT", 
  JOptionPane.INFORMATION_MESSAGE);
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
ta.setCaretPosition(0);
ta.setEditable(false);
]

1 个答案:

答案 0 :(得分:0)

您可能希望在用户输入值之后完成转换。您可以尝试将动作侦听器添加到JTextField组件。这是一个示例:

    SGEAC1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            String sgeac1tx = ((JTextField)e.getSource()).getText();
            int eac1sg = Integer.parseInt(sgeac1tx);

            System.out.println("SGEAC1 value = " + eac1sg);
        }
    });

请注意,当用户在字段中按Enter键时,将调用操作侦听器。