简体   繁体   中英

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM