This week's giveaway is in the Spring forum.
We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!
See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with a simple gui

 
Andrew Sepulveda
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
trying to do a simple ActionEvent but my problem is I get "button cannot be resolved to a variable"

affected code



whole class



Note: Its incomplete.
 
Stephan van Hulst
Bartender
Posts: 5334
48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, the error is pretty self-explanatory. It's looking for a variable button, but it can't find it. The button you're referring to in the go() method doesn't have the same scope as the button you're referring to in the actionPerformed() method.

I'd tell you to make a field named button, but the current way you're doing things is pretty terrible (no offense intended) and you should learn to stop using it immediately.

Instead of making your class implement ActionListener, register anonymous listeners with the button:
 
Andrew Sepulveda
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for helping me. sorry about the code, my knowledge is limited.

I never used Anonymous Listeners before. how does it work.
 
Stephan van Hulst
Bartender
Posts: 5334
48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anonymous classes are classes that don't have a name. As such, you can only make one instance of them, and you can't give them constructors. They are generally useful to create objects of a type you only use once. Listeners fit this bill, because you only want to create one instance of a listener and register it with one or more components.

You create an anonymous class by creating a new instance of a type, and then specifying how you want to override certain methods.
In this example, we create an anonymous class that extends/implements Whatever (which may be a class or an interface) and overrides the toString() method. We immediately make an instance of this 'nameless' class.

Now take a look at the example I gave before. I created an instance of a nameless class which extends AbstractAction. It passes the "Gamble" argument to the constructor of the AbstractAction class which takes only one String. It also implements the actionPerformed() method.
It's good to use an anonymous class here, because we only need one instance and don't care about its name, as long as it implements actionPerformed().

This instance of the nameless class gets assigned to the variable gamble, which we can then use where we want.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic