dio*_*231 4 java arrays swing java-8 eventhandler
我想在Java中为多个JButton添加一个EventHandler.我使用JButton数组JButton[] buttons = new JButton[120]
.我用过这个解决方案
for (int i=0; i<btns.length; i++){
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
Run Code Online (Sandbox Code Playgroud)
但我认为上面的代码很糟糕.
使用自定义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();
}
}
Run Code Online (Sandbox Code Playgroud)