Help with ActionListeners [message #990930] |
Sat, 15 December 2012 00:20 |
|
How would I go about passing a variable into a function inside an ActionListener()? This is my code.
for(int y = 0; y < 5; y ++) {
for(int x = 0; x < 5; x ++) {
currentRect = (y * 5) + x;
mainButtons.get(currentRect).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
answerField.setText(questions.get(currentRect).getAnswer());
}
});
}
}
The error is on line six, where it underlines "currentRect", and then complains about this,
Quote:Cannot refer to a non-final variable currentRect inside an inner class defined in a different method
What is does is iterate through a group of JButtons (javax.swing) , and then assign the appropriate action listeners based on their position in the ArrayList, however, I can't seem to pass the variable storing their positions into the actionlistener itself, so I'm stuck. I realised while im writing this that I should really use a foreach, so ill change that later. (just a little note to who was gonna point that out) I realize that I cannot also make that variable final, as it is changed during the for loop. I also tried passing the value of the currentRect ((y * 5) + x) into the functions, but to no avail.
andrewgies17
[Updated on: Sat, 15 December 2012 22:21] Report message to a moderator
|
|
|
|
Re: Help with ActionListeners [message #990996 is a reply to message #990974] |
Sun, 16 December 2012 14:56 |
|
On 12/15/2012 03:23 PM, Andrew Gies wrote:
> Anyone?
This isn't a forum for general Java questions, but about downloading,
setting up and using Eclipse.
I would suggest javaranch.com, jguru.com or stackoverflow.com
|
|
|
Powered by
FUDForum. Page generated in 0.04073 seconds