This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes JButton + ActionListeners Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JButton + ActionListeners Question" Watch "JButton + ActionListeners Question" New topic
Author

JButton + ActionListeners Question

Jack Lord
Greenhorn

Joined: Jun 04, 2004
Posts: 11
I've been trying out ActionListeners and run into a problem. I want pressing a button to make a label become visible and the text on the button itself to change, but I can't seem to do the second part from within the listener - I just get a nullPointerException. Can anyone tell me what I'm doing wrong?

Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

This a very common beginner mistake. You've got both a local variable and a member variable named "revealButton". When you initialize the variable in the constructor, it's the local one that gets set; the member stays null. But the actionPerformed method uses the member, so you get a NullPointerException. Solution: change

JButton revealButton = new JButton("Show answer");

to

revealButton = new JButton("Show answer");


You've made the same mistake with other variables, too.


[Jess in Action][AskingGoodQuestions]
Jack Lord
Greenhorn

Joined: Jun 04, 2004
Posts: 11
Ah, I see. Originally I had those variables just declared in the constructor, then when I couldn't access them from other methods I pasted the declarations up top. Pretty stupid of me really but I get so excited about building a GUI that I forget that the same rules apply to Swing objects as every other kind of object! Thanks for helping me out: much appreciated.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JButton + ActionListeners Question