This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma 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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JButton + ActionListeners Question" Watch "JButton + ActionListeners Question" New topic

JButton + ActionListeners Question

Jack Lord

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

Joined: Jul 08, 2003
Posts: 24199


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");


revealButton = new JButton("Show answer");

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

[Jess in Action][AskingGoodQuestions]
Jack Lord

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:
subject: JButton + ActionListeners Question
It's not a secret anymore!