How To Access Controls On a JPanel…?

2019-08-18 03:34发布

问题:

I'm a Java n0ob....so let me apologize in advance...

I've got a jPanel that I've added a bunch of controls to, dynamically, at run-time. Later, in my code, I want to loop through all of those controls (they are jCheckBoxes) to see if they are checked or not.

In .NET - I'd be looking at some like...

For Each myControl as Control In myPanel.Controls Next

Is there a way to accomplish that with the jPanel? Should I not be using a jPanel for this?

回答1:

Here is a method I wrote to set the font for all controls within a JPanel you could use something similar to access you CheckBoxes (Note it is recursive and goes through any child panels also).

public static final void setJPanelFont(JPanel aPanel, Font font)
{
    Component c = null;
    Component[] components = aPanel.getComponents();

    aPanel.setFont(font);
    if(components != null)
    {
        int numComponents = components.length;
        for(int i = 0; i < numComponents; i++)
        {
            c = components[i];
            if(c != null)
            {
                if(c instanceof JPanel)
                {
                    setJPanelFont((JPanel)c,font);
                }
                else
                {
                    c.setFont(font);
                }
            }
        }
    }
}  


回答2:

JPanel implements Container, just use its API.



回答3:

Simple... use getComponents method.



回答4:

You really should be keeping a list of these controls as you create them so that you don't have to loop through all of the components looking for check boxes. Create an ArrayList<JCheckBox> and add the check boxes to this array as you create them. Then, you already have references to them, and you can just loop through the array to see if they are checked. There's no need to loop through every component added to the panel.