If you want the same listener instance to listen to all the buttons in the frame, you need to force the actionPerformed method to collect all clicks and delegate based on the command:
public class listener extends ActionListener{ public void actionPerformed(ActionEvent e){ String command = e.getActionCommand(); if (command.equals("foo")) { handleFoo(e); } else if (command.equals("bar")) { handleBar(e); } } private void handleFoo(ActionEvent e) {...} private void handleBar(ActionEvent e) {...} }
which will become easier in Java 7 where you can switch lines! Button click ActionCommand will be a JButton Text attribute unless you set it otherwise
source share