简体   繁体   English

如何让单独的按钮做单独的事情?

[英]How do I make separate buttons do separate things?

I have a button in a simple application I'm making which will increment a variable by one once pressed.我正在制作的一个简单应用程序中有一个按钮,一旦按下它就会将变量加一。 This is it's code:这是它的代码:

public class GUI implements ActionListener {
    int clicks = 0;
    int autoClickLevel = 0;
    JLabel label;
    JFrame frame;
    JPanel panel;

    public GUI() {
        JButton button = new JButton("Click me!");
        button.addActionListener(this);

        panel = new JPanel();
        panel.setBorder(BorderFactory.createEmptyBorder(60, 100, 30, 100));
        panel.setLayout(new GridLayout(0, 1));
        panel.add(button);

        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

public static void main(String[] args) {
    new GUI();
}

@Override
public void actionPerformed(ActionEvent e) {
    clicks++;
}

I would like to know how to make a separate button (which I have already made, and it shows up; JButton button2 = new JButton("Click me too;"); ) which changes a separate variable.我想知道如何制作一个单独的按钮(我已经制作了它,它会显示出来; JButton button2 = new JButton("Click me too;"); )它会改变一个单独的变量。 button2.addActionListener(this); [plus different ways of doing it,] instead increments the clicks variable instead of a separate clicks2 variable. [加上不同的方法,] 而是增加clicks变量而不是单独的clicks2变量。

My code is a bit of a mess regarding this, and this second button's script doesn't work at all.我的代码对此有点混乱,第二个按钮的脚本根本不起作用。 I'm also fairly new to Java so I'm not much good at figuring out this either.我对 Java 也很陌生,所以我也不太擅长弄清楚这一点。 What's a good way to make the second button increment the other variable?使第二个按钮增加另一个变量的好方法是什么?

Have different ActionListeners.有不同的 ActionListener。 You can do this like this:你可以这样做:

button2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // do something
    }
});

Or you could define the ActionListener as its own class.或者您可以将 ActionListener 定义为它自己的 class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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