This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Can't acces For variable in inner class.  RSS feed

 
Paul Carter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code I have a loop which I use to create a set of buttons. At the same time I want to create an OnClick event for each button that runs a method to act upon the click depending on the text of the button.

When I try to compile the code below however I get an error in the new actionlistener:
"local variable buttonNo is accessed from within inner class; needs to be declared final"

What can I do to sort it out?

Thanks in advance

Paul.





private JPanel CreateTowerButtons(){
final String btnCaptions[] = {
"Yes/Buy", "Repeat", "No/End", "Haggle", "Bazaar", "Clear", "Tomb",
"Move", "Sanctuary", "DarkTower", "Frontier", "Inventory"};

final JButton[] towerButtons = new JButton[btnCaptions.length];

for (int buttonNo=0;buttonNo<towerButtons.length; ++buttonNo) {
towerButtons[buttonNo] = new JButton(btnCaptions[buttonNo]);

towerButtons[buttonNo].addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
PressedButton(towerButtons[buttonNo].getText());
}
});
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It may seem silly, but all you have to do is make a final copy of the variable before introducing the anonymous class; i.e.,

 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't access local variables from an inner class. The reason is the local variable may be out of scope when the inner class method gets executed.

Making the local variable final doesn't really address this issue -- it just allows the compiler to define another variable as the local variable's value does not change.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!