2

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. button2.addActionListener(this); [plus different ways of doing it,] instead increments the clicks variable instead of a separate clicks2 variable.

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. What's a good way to make the second button increment the other variable?

toydotgame
  • 45
  • 7
  • Although, the answer below is apt for your question, but you can also use the below version with every button as with you current button also without even implementing `ActionListener`. You can also set every button same as you've done for current button and can distinguish which button is pressed by following [this answer](https://stackoverflow.com/a/12828267/8244632). It's all your choice which way you prefer. – Lalit Fauzdar Jun 19 '20 at 09:20

1 Answers1

5

Have different ActionListeners. 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.