Skip to main content



      Home
Home » Newcomers » Newcomers » Help with ActionListeners(I can't pass a variable into an action listener?)
Help with ActionListeners [message #990930] Fri, 14 December 2012 19:20 Go to next message
Eclipse UserFriend
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) Smile 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.

[Updated on: Sat, 15 December 2012 17:21] by Moderator

Re: Help with ActionListeners [message #990974 is a reply to message #990930] Sat, 15 December 2012 17:23 Go to previous messageGo to next message
Eclipse UserFriend
Anyone?
Re: Help with ActionListeners [message #990996 is a reply to message #990974] Sun, 16 December 2012 09:56 Go to previous message
Eclipse UserFriend
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
Previous Topic:Cannot find plugin
Next Topic:Eclipse console
Goto Forum:
  


Current Time: Wed Jul 23 15:55:18 EDT 2025

Powered by FUDForum. Page generated in 0.13474 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top