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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With