How To Access Controls On a JPanel…?

元气小坏坏 提交于 2019-12-13 05:40:17

问题


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.



来源:https://stackoverflow.com/questions/3314183/how-to-access-controls-on-a-jpanel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!