1

I got a whole bunch of buttons, is there a way of adding actionListeners to all of them without going button.addActionListeners(this) for all of them? it makes the code looks so messy.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Tom Lilletveit
  • 1,872
  • 3
  • 31
  • 57

3 Answers3

3

If you want common behavior to all your buttons you need to make them extends an abstract class where you defined the common code. So define your own abstract MyButtonClass with its own add listener method.

Alain BUFERNE
  • 2,016
  • 3
  • 26
  • 37
3

No, there is not. But if all the buttons share the same action listener (which is quite strange), maybe they should be stored in an array or collection. You could then do:

for (JButton button : allButtons) {
    button.addActionListener(this);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

If all the buttons are on a single container you could register a single ActionListener like this:

for (Component c: container.getComponents()) {
   if (c instanceof JButton) {
      ((JButton)c).addActionListener(this);
   }
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276