Win a copy of Fixing your Scrum this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

Can't acces For variable in inner class.

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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());
}
});
}
 
author and iconoclast
Posts: 24203
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.,

 
author
Posts: 23905
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic