As janos said, adding an action listener to each button does the job well, but in large code, when you need to add a lot of buttons, it doesn't look too neat, I suggest you use setActionCommand() for the JButton that you create, using simple, you implement the ActionListener in the JFrame just like you do, but after each button add
button.addActionListener(this); button.setActionCommand("commandname")
And you can do it just like buttons as you want, now, to run these commands correctly, your action, performed by you, should look like this:
@Override public void actionPerformed (ActionEvent e) { String cmd = e.getActionCommand(); switch(cmd) { case "action1": // Do something break; case "action2": // Do something else break; case "potato": // Give Mr. chips a high five break; default: // Handle other cases break; } }
And so on, again, another solution works fine, I just personally think it is very neat, especially in code where you have a lot of listeners for actions.
source share