Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 264
dios231 Avatar asked Mar 13 '23 18:03

dios231


1 Answers

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();
     }
}
like image 176
Mohammed Aouf Zouag Avatar answered Mar 23 '23 23:03

Mohammed Aouf Zouag