Ok, so I couldn’t find exactly what I needed anywhere else, so here goes.
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,
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.
Thanks,
andrewgies17
The solution is simple, simply declare a new final variable inside of your block:
or if you need the value of currentRect outside of the block:
and you use currentRect2 instead of currentRect in your anonymous class. This is counterintuitive because it looks like that the final variable is beeing re-initialised each time but in fact, you must see this as a new variable that is initialised only once for each loop of the block.
However, this is not the most intelligent way of solving this problem; because you are creating a brand new anonymous class for each button just for the purpose of storing a small value that is different between them. These can quickly add up on a limited device. A better idea would be to store the value of the currentRect as a tag for each button. This way, you can declare a single instance of the anonymous class in the outer class and reuse it for all buttons.