Search code examples
javaswingarraylistjcomponent

Storing array of Components(panel.getComponents()) to Array List


I have 3 checkboxes and planning to add more and I need to determine if it is checked or not. So what I did was to put them in an ArrayList of JCheckBox. By the way, I'm using SMALLINT apache derby data type on which ill use preparedStatement.getBoolean();

ArrayList<JCheckBox> homeCbxs = new ArrayList<>();
homeCbxs.add(updateUserNameCheckBox); // 0
homeCbxs.add(updatePasswordCheckBox); // 1
homeCbxs.add(updatePhotoCheckBox); // 2

int x = 0; 
for(JCheckBox cb : homeCbxs){
    Boolean bool;
    bool = cb.isSelected();
    //preparedStatement here, ps.setInt(x,bool)
    x++;
}

I thought maybe I can use the getComponents() method which returns an array of components so I can get all the check boxes inside a panel.

Maybe like,

ArrayList<JCheckBox> homeCbxs = homePermssionsCheckBoxPanel.getComponents();

Instead of adding them one by one,

homeCbxs.add(updateUserNameCheckBox); // 0
homeCbxs.add(updatePasswordCheckBox); // 1
homeCbxs.add(updatePhotoCheckBox); // 2

However, the problem is ArrayList<JComponents> won't accept arrays. I get an error message that incompatible types: Component[] cannot be converted ArrayList<JCheckBox>

Do you have any suggestions? Any workaround to cast or do some conversions. I'm just trying to shorten the lines of codes. :D

Also, I would like to ask if getComponents() assigns 0 as first index of it's array.

I'd appreciate any help.


Solution

  • Create your own utility method to get the components.

    public List<Component> getComponentsAsList (Container cont){
        return Stream.of(cont.getComponents())
                     .collect(Collectors.toList());
    }
    

    Then, you just have to not forget to cast them to JCheckBox to check if they're checked or not.

    List<Component> list = getComponentsAsList(homePermssionsCheckBoxPanel);
    
    for(Component c : list){
        if (!(c instanceof JCheckBox)) continue;
        if (((JCheckBox)c).isSelected()){
            // doStuff
        }
    }
    

    public List<Component> getComponentsAsList (Container cont){
        List<Component> tmp = new ArrayList<>();
        for (Component c : cont.getComponents()) {
            tmp.add(c);
        }
        return tmp;
    }