sherrellbc
sherrellbc

Reputation: 4853

How to increment through ArrayList and change its state?

I have a series of JCheckBox instances and I want to reset their state to unchecked using .setSelected(false), but I am unsure how to do this. I figured it was something like below, but it would not compile.

ArrayList<JCheckBox> checkboxList; //initialized in this manner earlier in code


    public class MyResetListener implements ActionListener {
    public void actionPerformed(ActionEvent a){
         for(JCheckBox a : checkboxList){
             checkboxList.setSelected(false);
         }
    }
}

I tried this with a normal for loop as well, but was unsure how to access the ArrayList either way.

    public class MyResetListener implements ActionListener {
    public void actionPerformed(ActionEvent a){
         for(int i=0; i<256; i++){
             checkboxList[i].setSelected(false);
         }
    }
}

Upvotes: 0

Views: 252

Answers (3)

Bernhard Barker
Bernhard Barker

Reputation: 55589

It should just be:

for(JCheckBox b: checkboxList)
    b.setSelected(false);

I renamed a to b as a was already defined here - ActionEvent a.

b is the variable you're getting from the collection as you're iterating through it, thus you have to use that instead of checkboxList, which is the whole ArrayList.

Or:

for(int i = 0; i < checkboxList.size(); i++)
   checkboxList.get(i).setSelected(false);

Java classes (i.e. ArrayList) don't natively support the [] operation (though you do get extensions, and arrays are technically classes as well, and they do support it). ArrayList has a get method to get element from it.

Upvotes: 3

cifz
cifz

Reputation: 1078

If I get you correct for accessing an element in an ArrayList you can use the get method.

Your example will looks like:

     for(int i=0; i<256; i++){
         checkboxList.get(i).setSelected(false);
     }

Upvotes: 0

earcam
earcam

Reputation: 6682

Instead of using array subscripts you must use methods, like get()

e.g.

checkboxList.get(i).setSelected(false);

Upvotes: 1

Related Questions