tags:

views:

348

answers:

3

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

A: 

Well, if you have your checkboxes in an array... you can do it in a loop.

JCheckBox[] myBoxes = new JCheckBox[200];

//Some creation stuff here

for (int i=0; i<myBoxes.length; ++i) {
   if (myBoxes[i].isSelected()) {
       //Do stuff!
   }
}
Malaxeur
No. They are not in an array. Actually the GUI code is a generated code so I can't change that code.
Yatendra Goel
Oh that's BRUTAL. You can do this by reflection in a loop if you're really lazy... however an alternative is to make a method to handle the checkbox logic and just call handleCheckbox(checkbox1)... that way only the handleCheckbox method is written a bajillion times
Malaxeur
+1  A: 

Ummm, what should I say?

OK, You should starts by using array to hold all check boxes you have so you can loop through it.

In case that is too late, you may have a another choice by loop though all elements on that container (only work if all checkboxes are on the same container). Something like 'jPanel1.getComponents()' and then loop them only see which is a Checkbox.

Anyway .. I think, you should put all those in an array and save yourself from a variable mess.

NawaMan
You answer is also an accepted answer but I can mark only one answer as accepted answer. Sorry for that but a lot of thanks for your answer.
Yatendra Goel
No problem ... :D
NawaMan
+3  A: 

You really should have put these in an array or Collection so that you can just loop over them. eg.

List<JCheckBox> allCheckBoxes = new ArrayList<JCheckBox>()
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

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html

http://java.sun.com/docs/books/tutorial/collections/index.html

Tom Martin