如何将函数添加到 Button 类,该函数将在 Processing/java 中单击时执行



我做了一个名为 Button 的类;在构造函数中,我绘制了一个按钮。但是,我想为该构造函数提供一个类名,例如主菜单或设置,单击按钮时将执行该构造函数。在 Java 中对此进行编程的正确方法是什么?

这是为了学校作业

感谢您的帮助!

我建议在"main"方法或构造函数中使用actionListener。

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
class test {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setSize(100,100);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        JButton button = new JButton("Click me");
        f.add(button);
        f.addActionListener (new ActionListener () { //<---this is the important part
            public void actionPerformed(ActionEvent e) {
                //do whatever you need to do here
            }
        });
    }
}

您可能会受到此处理教程的启发或者你应该使用一些库来创建带有 controlP5 等按钮的菜单

最新更新