One event handler for multiple JButtons

I want to add an EventHandler for several JButtons in Java. I am using 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.

+4
source share
1 answer

Use 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();
     }
}
+7
source

Source: https://habr.com/ru/post/1621862/


All Articles