aspose file tools*
The moose likes Beginning Java and the fly likes Help with a simple gui Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help with a simple gui" Watch "Help with a simple gui" New topic
Author

Help with a simple gui

Andrew Sepulveda
Greenhorn

Joined: Oct 02, 2011
Posts: 10
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

Joined: Sep 20, 2010
Posts: 3649
    
  17

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

Joined: Oct 02, 2011
Posts: 10
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

Joined: Sep 20, 2010
Posts: 3649
    
  17

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Help with a simple gui