AloneInTheDark
AloneInTheDark

Reputation: 938

Java Swing: Enabling/Disabling specific type of components

I need to enable/disable some components inside a JFrame. But i only want to disable these types:

JTextField
JButton
JComboBox

Is there any simple example about doing that kind of things in java?

Upvotes: 1

Views: 115

Answers (2)

NESPowerGlove
NESPowerGlove

Reputation: 5496

Loop through all the components of the JFrame, including components inside other components, and do an instanceof check to see if it's one of the types you want to disable, if so, disable the component.

As an example on how to do this, one could enable or disable all JButtons with the following function :

public void flipEnabledOnAllButtons(boolean enabled, Container rootContainerToSearch)
{    
    for (Component c : rootContainerToSearch.getComponents())    
    {    
        if (c instanceof Container)    
        {    
            flipEnabledOnAllButtons(enabled, (Container)c);    
        }    

        if (c instanceof JButton)    
        {    
            c.setEnabled(enabled);    
        }      
    }
}

Upvotes: 3

camickr
camickr

Reputation: 324108

Check out Darryl's Swing Utils. You can use the class to get a List of components of a specific class. Then you iterate through the list to do your processing.

Ro example to get al the combo box compnents you could uee:

List<JComboBox> components = SwingUtils.getDescendantsOfType(JComboBox.class, frame.getContentPane(), true);

Upvotes: 1

Related Questions