Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

NullPointerException in my First AWT program  RSS feed

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting NullPointerException...


[This message has been edited by Paul Wheaton (edited April 04, 2000).]
 
paul wheaton
Trailboss
Posts: 22261
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I stuck a couple of [ code ] statements in so the program formatting wouldn't be lost.
At what point do you get the exception?
I do see this line:
but[a] = new Button(keys[0]);
Maybe it should be keys[ a ]
Now I see the problem. The line
Panel pc = new Panel();
should be
pc = new Panel();
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see Paul has just answered the specific question, so I'll just add some general comments. When you get a run-time error, look carefully at the error message you see. It will usually tell you exactly what line the error occurred on. (If not, try compiling with -g - that may help.) In this case, the error message I see is:
<code><pre>Exception in thread "main" java.lang.NullPointerException
at Hang1.addCom(Hang1.java:28)
at Hang1.main(Hang1.java:51)</pre></code>
This tells us that main() line 51 called addCom(). Within addCom(), line 28 threw a NullPointerException. So look at line 28:
<code><pre> pc.add(but[a]);</pre></code>
This narrows the search down considerably. What could be null here? pc? but? a? If you're not sure, it's easy to add statements just before it:
<code><pre> System.out.println("pc: " + pc);
System.out.println("but: " + but);
System.out.println("a: " + a);</pre></code>
This way, you can learn that pc is the one that's null. So now you know to look carefully at all statements involving pc. Where is it supposed to be assigned a non-null value? Is that statement executing? What value does pc have afterwards? Etc. In this way you can narrow down the search considerably.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!