Search code examples
javaswingjbuttonactionlistener

Should i use different instances of a single ActionListener for multiple buttons?


I have a single ActionListener for multiple buttons:

private class MyActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            if (event.getSource().equals(button1)) {
                // do something
            } else if (event.getSource().equals(button2)) {
                // do something else
            }
        }
}

Which one of the following is the better way to add the ActionListener to these buttons and why?

1.:

button1.addActionListener(new MyActionListener());
button2.addActionListener(new MyActionListener());

2.:

MyActionListener mal = new MyActionListener();

button1.addActionListener(mal);
button2.addActionListener(mal);

I went with the 2nd option, but not sure it's the proper way.


Solution

  • This question asks for opinion and may be closed, and because of this, I'm answering as a community wiki, but I think the best answer is "it depends".

    What I do is if all listeners are exactly the same, and you're not passing anything different into each constructor, then just have each button share the same listener. If I need to pass unique information into the listeners, then I use separate listeners, but really either will work, and neither will likely cause an appreciable difference in program operation or responsiveness.