4

I want to add an EventHandler for multiple JButtons in Java. I use a JButton array JButton[] buttons = new JButton[120]. I used this solution

        for (int i=0; i<btns.length; i++){
        buttons[i].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
    }

but i think the above code is bad.

dios231
  • 714
  • 1
  • 9
  • 21

1 Answers1

7

Use a custom ActionListener:

CustomActionListener listener = new CustomActionListener();

for (int i=0; i<btns.length; i++){
   buttons[i].addActionListener(listener);
}

class CustomActionListener implements ActionListener {
     public void actionPerformed(ActionEvent e) {
         // Handle click on buttons
         // Use e.getSource() to get the trigger button
         JButton button = (JButton) e.getSource();
     }
}
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • i followed your solution but inside `actionPerformed`, the command `e.getSource().setText("OK"` throws an error. – dios231 Dec 27 '15 at 13:01
  • what error do you get ? (Are you casting `e.getSource()` to a `JButton` before calling `.setText()` ?) – Mohammed Aouf Zouag Dec 27 '15 at 13:02
  • i implement this `class CustomActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { JButton btn = new JButton(); btn = (JButton) e.getSource(); btn.setText("OK"); } }`. But i still think this code is dirty. – dios231 Dec 27 '15 at 13:09
  • thanks dude. I start learning java 2 weeks ago and i'm still a newbie. – dios231 Dec 27 '15 at 13:16