aspose file tools*
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
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: 36513
    
  16
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: 24166
    
  30

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: 36513
    
  16
Well done
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Trying to change the text on a button when clicked - crasches....
 
Similar Threads
Jtable and database results
Help with getting the database to take values (Java-MySQL)
NullPointerException on swing
Remove comma in the JSpinner
One central controller and 4 compas buttons