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