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.
Asked
Active
Viewed 116 times
1

mKorbel
- 109,525
- 20
- 134
- 319

Tom Lilletveit
- 1,872
- 3
- 31
- 57
-
This is precisely what collections and `for` loops are for. – Hovercraft Full Of Eels Oct 28 '12 at 18:32
-
`it makes the code looks so messy.` sorry really ???, don't extend class or implements whatever – mKorbel Oct 28 '12 at 19:14
3 Answers
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