Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why dont this work?  RSS feed

 
Karis Brown
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inside of the "public void init()" method, you need to remove the Type declaration on "Calc" and "response".

Actually the second line is the problem. As it currently stands, you have an instance variable named "response" that is initially set to null. Inside of the "init()" method you re-declare "response" so that the instance variabled is shadowed. A new [local] variable called "response" is declared, initialized, used, and then it goes out of scope.
The UI looks fine, but the "response" instance variable is still null, so in the "actionPerformed()" method when you try and access it you get a NULL POINTER exception.
This is a very common mistake. Don't re-declare your instance variables.
 
Craig Wood
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the error your code generates:

Why? Count down to the given line (32 here but I've added some comments to the top of the file so it will be different for the code in your post). You declared JTextField response as a class varible but did not instantiate it. Instead you declared and instantiated it JTextField response = new JTextField(10); inside init.

Scope. What you declare inside curley braces (eg, init) is private to that scope, nobody outside the curley braces can see it. The curley braces define the scope of the variable you declare within them.

From the point of view of the actionPerformed method, response has been declared (in class scope, same as actionPerformed is in) but ha not been initialized. actionPerformed cannot see the JTextField instance response that was declared and instantiated within init.

The response delcared and instantiated inside init has no relationship to the response delcared in class scope above/outside init. So when you try to call a method on response you cause a NullPointerException, there is no JTextField named response - it never was instantiated. In other words, response is a reference to a JTextField that does not exist (has not been instantiated).
Here's one way fix it:
 
Karis Brown
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YOU R A GENIUS MATE THANKS!
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!