Reputation: 314
I am using Java Swing and i want to change a variable on each radio button selection. I am new to Java and I am not really sure where I am slipping up here...
String[] test = {"red","blue","green","yellow"};
for(final int i=0; i < test.length; i++)
{
RadioItem = new JRadioButtonMenuItem(test[i]);
RadioItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
settingSelection = test[i];
JOptionPane.showMessageDialog(null,test[i]);
};
});
settings.add(RadioItem);
mnSettings.add(RadioItem);
}
The error I get is:
The final local variable i cannot be assigned. it must be blank and not using a compound assignment.
Can anyone assist?
Upvotes: 1
Views: 181
Reputation: 2100
You can declare a variable within a for loop
for(int i = 0; i < 10; i++)
what you have done is declare a final variable within the for loop. This can't be done. A final variable cant be changed, its value is set and nothing can change it
Take out the final
and just have your loop like for(int i = 0; i < test.length; i++)
Upvotes: 0
Reputation: 37023
It's complaining about line:
for(final int i=0; i < test.length; i++)
Here in for loop, you defined i as final and then you are changing the value of i as well (working of for loop). So change it to:
for(int i=0; i < test.length; i++)
Final field or object assigned once cannot be re-assigned another value again.
Upvotes: 1
Reputation: 9687
Remove the final keyword from the loop:
for(int i=0; i < test.length; i++)
Upvotes: 0