关于AbtractButton的GUI

问题描述 投票:0回答:1

我是GUI的新手,在我尝试学习时遇到了一些问题。好的,这是我的代码。

public class Sample implements ActionListener{

public void go() {
    JButton button = new JButton("Click");
    JFrame frame = new JFrame();
    frame.getContentPane().add(button);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100,100);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e){
            button.setText("Hello");
        }
    });   
}

它一直告诉我,AbstractButton类型中的方法addActionListener(ActionListener)不适用于参数(new ActionListener(){})。我没有得到它,因为我记得我以前做过,它可以工作。 ......

java user-interface jbutton
1个回答
0
投票

我没有收到错误但是动作监听器不起作用,因为动作执行的ActionListener接口方法需要重写。

button.addActionListener(new ActionListener() {
    // add the annotation below
    @Override
    public void actionPerformed(ActionEvent e) {
        button.setText("hello");
    }
});

通常你会在main方法中构建JFrame。后来他们添加了一个Invoke Later运行器,当类扩展JFrame时,它将以更面向对象的方式创建窗口。

public class App extends JFrame {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new App();
                    frame.setVisible(true);
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    public App(){
        JButton button = new JButton("Click");
        getContentPane().add(button);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(100,100);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                button.setText("hello");
            }
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.