Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 8 in Action this week in the Java 8 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: 24168
    
  30

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
 
Similar Threads
Frames
Some code about GUI
Problem with opening new JPanel when separated into different classes
Java Board Game
buttons that are not same size