简体   繁体   中英

How to add a function to a Button class which will be executed when clicked in Processing/java

I made a class called Button; In the constructor I draw a button. However I want to give a class name for instance a MainMenu or Settings to that constructor which will be executed when clicked on the button. What's the proper way to program this in Java.

It's for a school assignment

Thanks for your help!

I recommend using an actionListener, either in the "main" method, or a constructor.

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之类的按钮的菜单

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM