my dog learned polymorphism*
The moose likes Beginning Java and the fly likes JButton button Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "JButton button" Watch "JButton button" New topic
Author

JButton button

david john
Greenhorn

Joined: Oct 16, 2008
Posts: 16
This code compiles and runs fine. But if inside the go method while creating the instance of JButton if we mention it like JButton button = new JButton("click this") then it throws nullPointerException when we click on the button. I am not able to understand what is going wrong if reference type is also mentioned during the instance creation.
Thank you in advance.
This code will work

This code will throw nullPointerException.

[ November 23, 2008: Message edited by: david john ]
Andre Uhres
Greenhorn

Joined: Nov 23, 2008
Posts: 23
The reference to "button" in the "actionPerformed" method
does not know the button that you declare locally in the "go" method.
So, an Exception is thrown, because the instance variable "button"
is not initialised.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by david john:
... I am not able to understand what is going wrong if reference type is also mentioned during the instance creation...

To expand on what Andre said, when you specify the type before the variable name, you are declaring a new variable instead of using an existing variable. In this example, you have 2 different variables called "button." One is declared as an instance variable in the class guiAct, and the other is declared as a local variable within the scope of the method go. The "button" inside go is assigned to an instance, but the "button" in guiAct has a default value of null.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
david john
Greenhorn

Joined: Oct 16, 2008
Posts: 16
Marc, Andre... Thank you very much for the reply! Got the point.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JButton button
 
Similar Threads
Getting Java running on RHEL 5
Button's action event in Head first java
New to GUI, need help with actionListener and buttons
code error
function scope?