I'm trying to set all the checkboxes' value to setSelected(false)
. These checkboxes are from different subpanels that has other subpanels. getComponents(panelName)
only gets the components contained on it but not every subpanel/child panel of child panel... and so on.
In the above,allPermissionsJPanel
is the parent panel. settingsButtonPanel
and cardContainerPanel
as first level subpanel and I want every single JCheckBox
to be set to false.
How do I do that? I tried using getComponents()
but it's not returning all the checkboxes from subpanel of subpanels.
This is my code.
List<Component> allPermissionsCheckboxes =fm.getComponentsAsList(allPermissionsJPanel);
for(Component c: allPermissionsCheckboxes){
if(c instanceof JCheckBox){
((JCheckBox) c).setSelected(false);
}
}
I tried checking other methods related to getComponents()
but I didn't find a method that goes through every subpanel of subpanel so I can check if it's an instanceof
a JCheckBox
. Any suggestions?
You'll want to implement this as a recursive method that iterates through the component hierarchy looking for check boxes and performing setSelected(false)
.
The method could look something like this:
public void deselectAllCheckBoxes(Component panel) {
List<Component> allComponents = fm.getComponentsAsList(panel);
for (Component c : allComponents) { // Loop through all the components in this panel
if (c instanceof JCheckBox) { // if a component is a check box, uncheck it.
((JCheckBox) c).setSelected(false);
} else if (c instanceof JPanel) { // if a component is a panel, call this method
deselectAllCheckBoxes(c); // recursively.
}
}
Then all you have to do is call deselectAllCheckBoxes(allPermissionsPanel);