I have a JPanel with many objects, and one main action that can be performed: a calculation. There is a button to do this, but also a JTextField and other components in which the user might want to press enter in. For example, if you are selecting something from a JComboBox and press enter, the calculation will happen. Is there an easy way to add such a listener to all the contents from a JPanel, instead of adding actionListeners to every single component?
Asked
Active
Viewed 3,562 times
3 Answers
1
JPanel
extends JComponent
, that inherits Container
. You can use getComponents()
. You get a Component[]
array, which you can loop through and add for each component, that is a subclass of Component
like Button
, and add the same ActionListener
for each component. See http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html

cinhtau
- 1,002
- 8
- 16
-
2You would probably need to use recursion to do this as components may well be nested in containers. – Hovercraft Full Of Eels May 03 '13 at 21:11
-
@Hovercraft Full Of Eels [I know (very fragile if not used correctly) very simple, settable, based on String value, can be generated as parameters on fly](http://stackoverflow.com/questions/9007259/giving-jmenuitems-name-to-its-actionlistener/9007348#9007348) – mKorbel May 03 '13 at 22:17
0
@cinhtau has the right approach. It's made a bit more difficult by the fact that there is no common type that has an 'addActionListener' method. You have to check for each case that you want to add the action listener for.
public static void addActionListenerToAll( Component parent, ActionListener listener ) {
// add this component
if( parent instanceof AbstractButton ) {
((AbstractButton)parent).addActionListener( listener );
}
else if( parent instanceof JComboBox ) {
((JComboBox<?>)parent).addActionListener( listener );
}
// TODO, other components as needed
if( parent instanceof Container ) {
// recursively map child components
Component[] comps = ( (Container) parent ).getComponents();
for( Component c : comps ) {
addActionListenerToAll( c, listener );
}
}
}

wolfcastle
- 5,850
- 3
- 33
- 46
0
thats what i did right now and it worked
private void setActionListeners() {
for (Component c : this.getComponents()){
if (c.getClass() == JMenuItem.class){
JMenuItem mi = (JMenuItem) c;
mi.addActionListener(this);
}
if (c.getClass() == JCheckBoxMenuItem.class){
JCheckBoxMenuItem cmi = (JCheckBoxMenuItem) c;
cmi.addActionListener(this);
}
}
}

Korialstrazh
- 1
- 1