I have around 200 hundred checkboxes in a Java GUI. Now I want to have the list of all checkboxes that have been checked by the user.
I can do it in one way like this:
jCheckBox1.isSelected();
But I don't want to write this line for 200 checkboxes. Is there any way to do this through a for loop.
all the checkboxes have the name like jCheckBox1, jCheckBox2, jCheckBox3, jCheckBox4 ... jCheckBox200
解决方案
You really should have put these in an array or Collection so that you can just loop over them. eg.
List allCheckBoxes = new ArrayList()
allCheckboxes.add(new JCheckBox());
etc.
If you have all these checkboxes declared as members then there's no excuse to just put them in a list instead.
In the meantime you could use a dodgy cast in a for loop (if all the checkboxes are on the same panel)
boolean allSelected = true;
for(Component component : myPanel.getComponents()) {
if(component instanceof JCheckBox) {
allSelected &= ((JCheckBox)component).isSelected();
}
}
I'd recommend reading about Java arrays and collections before continuing