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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.