开发者

How To Access Controls On a JPanel...?

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

I开发者_JAVA技巧s there a way to accomplish that with the jPanel? Should I not be using a jPanel for this?


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


JPanel implements Container, just use its API.


Simple... use getComponents method.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜