• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JButton + ActionListeners Question

 
Jack Lord
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jack Lord
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic