如何从JTextField逐个获取2个不同的整数值

时间:2013-09-18 09:54:23

标签: java swing jtextfield

我正在使用swing制作一个java计算器,我有几个数字按钮&操作按钮,假设当我按7,7在TextField上打印,然后我按'*',结果7被删除,再按3,3打印,我按'=',然后我的答案是49而不是21。

这是我的代码:

//ob16 is a button for '*'operation & adding an action//
ob16.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // for getting the 1st integer from textfield //

        String v = textField.getText();
        // changing the type for performing '*' operation//

        final int y = Integer.parseInt(v);

        // defining the class's object which is having method asap1()//
        asap k = new asap();

        k.asap1();

        // for getting the 2nd integer from Text field//  
        String l = textField.getText();

        final int j = Integer.parseInt(y);

        //ob22 is a '=' button & adding an event for it//

        ob22.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int m = y * j;
                System.out.println("" + m);
                textField.setText("" + m);
            }
        });
    }
});
ob.setVisible(true);// ob is a frame//
…
class asap extends mini {

    public void asap1() {

        //ob2 is a Backspace button in my calculator & adding an event for it//     
        ob2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText(null);
            }
        });
    }
}

我知道为什么我得到了错误的答案,但我想知道执行此操作的正确程序。

1 个答案:

答案 0 :(得分:1)

您正在另一个ActionListener中添加ActionListener,这样每次调用+按钮的操作时,它都会为=按钮创建一个新的动作侦听器。这将导致=按钮具有多个动作侦听器。