Search code examples
javaitemlistener

addItemListener with for-loop not possible


To shorten my code I started constructing lists with the components needed in my java project to access them with a simple for-loop.

As everything works I wanted to add ItemListeners to the components in the list:
checkBoxes.get(0).addItemListener(){/*including code here*/}
works totally fine, however I would like to set them with a loop as well. So I tried this:

for (int i=0; i<=10; i++){
    checkBoxes.get(i).addItemListener(new ItemListener){
        public void itemStateChanged(ItemEvent arg0){
           someMethod(i);
        }
    });
}

as the checkBoxes are supposed to trigger another method based on their index. I get the compiler error:

Local variable i defined in an enclosing scope must be final or effectively final

So I assume that I cannot add ItemListeners in this dynamic way? Is there a way around this?

After a second of testing it seems I cannot use i at all?


Solution

  • As the compiler says, i needs to be final.

    To achieve this you could use an intermediate final variable in the loop.

    for(int i=0; i<checkBoxes.size(); i++) {
        final int finalI = i;
    
        checkBoxes.get(i).addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent arg0){
                someMethod(finalI);
            }
        });
    }