Search code examples
javaswingjframejcheckbox

How to check what checkboxes are checked within a JFrame?


I have several checkboxes within a JForm(SubComponents) and I am using this code to check which one's are checked:

countItems = 0;
    for(Component jb: this.getComponents())
    {
        if((jb instanceof JCheckBox) ) //I never get pass this point(its always false)
        {   
            JCheckBox chbox = (JCheckBox)jb;
            if(chbox.isSelected())
            countItems++;
        }
    }

Does anyone know what the problem is?

Thank you

EDIT: Here is xml:

<Form version="" maxVersion"" type="">
   <AuxValues>
   </AuxValues>
   <Layout>
   </Layout>
   <SubComponents>
     <Component class="javax.swing.JCheckBox" name="jCheckBox1">
       <Properties>
         <Property name="text" type="java.lang.String" value="Cheese"/>
       </Properties>
     </Component>
     <Component class="javax.swing.JCheckBox" name="jCheckBox2">
       <Properties>
         <Property name="text" type="java.lang.String" value="Sausage"/>
       </Properties>
     </Component>
     <Component class="javax.swing.JCheckBox" name="jCheckBox3">
       <Properties>
         <Property name="text" type="java.lang.String" value="Pepperoni"/>
       </Properties>
     </Component>
     <Component class="javax.swing.JCheckBox" name="jCheckBox4">
       <Properties>
         <Property name="text" type="java.lang.String" value="Mushroom"/>
       </Properties>
     </Component>
  </SubComponents>
</Form>

Solution

  • Maybe your checkboxes are inside another container such as JPanel in that case you should call getcomponents on the container components, otherwise you could create a method that you call recursively when you find another container components inside the jframe, so you can traverse all hierarchy ...