dios231 dios231 - 4 years ago 120
Java Question

One Event Handler for multiple JButtons

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.

Answer Source

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();
     }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download