Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trying to change the text on a button when clicked - crasches....

 
Peter Hammar
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

The code below compiles, but when I click on the spelarJB the program crashes.



The error messages:



What have I missed?

Regards
H
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have declared the button twice, once as a field and once as a local variable. The local variable is initialised, goes out of scope, and the field is left as null.
 
Peter Hammar
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But otherwise I get this:



Where should I create the button so that the actionPerformed method can see it?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are 2 distinct variables named spelarJB -- one is a member, shared by all methods, the other declared in the createGUI() method. This latter one is the one being initialized, but your event handler is expecting the former one to be. In CreateGUI, don't say "JButton spelarJB =" -- just say "spelarJB =". This is a common mistake!
 
Peter Hammar
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for your time and help it works now
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic