• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JButton button

 
david john
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
david john
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marc, Andre... Thank you very much for the reply! Got the point.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic