Question

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?

Was it helpful?

Solution

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

OTHER TIPS

@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 );
        }
    }
}

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);
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top