This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Trying to change the text on a button when clicked - crasches.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Trying to change the text on a button when clicked - crasches...." Watch "Trying to change the text on a button when clicked - crasches...." New topic
Author

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

Peter Hammar
Ranch Hand

Joined: Mar 01, 2010
Posts: 34
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

Joined: Oct 13, 2005
Posts: 38441
    
  23
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

Joined: Mar 01, 2010
Posts: 34
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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!


[Jess in Action][AskingGoodQuestions]
Peter Hammar
Ranch Hand

Joined: Mar 01, 2010
Posts: 34
Thanks a lot for your time and help it works now
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Well done
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Trying to change the text on a button when clicked - crasches....