Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Newcomers » Newcomers » Help with ActionListeners(I can't pass a variable into an action listener?)
Help with ActionListeners [message #990930] Sat, 15 December 2012 00:20 Go to next message
Andrew Gies is currently offline Andrew GiesFriend
Messages: 12
Registered: October 2012
Junior Member
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.


andrewgies17

[Updated on: Sat, 15 December 2012 22:21]

Report message to a moderator

Re: Help with ActionListeners [message #990974 is a reply to message #990930] Sat, 15 December 2012 22:23 Go to previous messageGo to next message
Andrew Gies is currently offline Andrew GiesFriend
Messages: 12
Registered: October 2012
Junior Member
Anyone?

andrewgies17
Re: Help with ActionListeners [message #990996 is a reply to message #990974] Sun, 16 December 2012 14:56 Go to previous message
Russell Bateman is currently offline Russell BatemanFriend
Messages: 3798
Registered: July 2009
Location: Provo, Utah, USA
Senior Member

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: Thu Apr 18 13:15:07 GMT 2024

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

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

Back to the top