JButton Action Listener不起作用

时间:2014-08-02 19:21:23

标签: java swing user-interface actionlistener

我正在为mt GUI计算器上的JButtons设置动作监听器。为了测试这个,我设置了当我按下计算器上的第一个按钮时将显示更改为新消息。但是,它不起作用。任何建议将不胜感激!非常感谢!

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class GUICalculator extends JFrame{

    //Fields
    JButton[] buttons = new JButton[16];
    String s = "0.0";

    public GUICalculator(){
        Font font1 = new Font("Monospaced", Font.BOLD, 20);
        NumberListener numListen = new NumberListener();

        //Create JPanel p1
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(4, 4, 10, 20));
        String buttonValues[] = {"1", "2", "3", "+",
                                 "4", "5", "6", "-",
                                 "7", "8", "9", "*",
                                 "0", ".", "C", "/"};

        for(int i = 0; i < 16; i++){
            JButton button = new JButton(buttonValues[i]);
            buttons[i] = button;
            buttons[0].addActionListener(numListen);
            p1.add(buttons[i]);
        }

        //Create text field
        JTextField text = new JTextField();
        text.setText(s);
        text.setEditable(true);
        text.setFont(font1);

        //Create JPanel p2
        JPanel p2 = new JPanel();
        p2.setLayout(new BorderLayout(10, 20));
        p2.add(p1, BorderLayout.CENTER);
        p2.add(new JButton("="), BorderLayout.SOUTH);
        p2.add(text, BorderLayout.NORTH);

        //Add contents to the frame
        add(p2, BorderLayout.CENTER);
    }
    public static void main(String[] args) {

        GUICalculator frame = new GUICalculator();
        frame.setTitle("Calculator");
        frame.setSize(300,300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private class NumberListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == buttons[0]){
                s = "It worked!";
            }
            else{
                s = "It did not work";
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

添加尚未在ActionListener注册的按钮时,您正在创建新的按钮实例。替换

p1.add(new JButton(buttonValues[i]));

p1.add(buttons[i]);