views:

275

answers:

3

Why do I get a null pointer exception when I try and run this on a label:

JLabel player1CurrentScore = new JLabel("" + matchPlay.returnPL1GamesWon(),
                                        JLabel.CENTER);

Is it because I cannot have two strings concatenated like this?

Ideally, I am trying to set the label as the score of the player so it can be incremented correctly as and when is needed.

Here is my Exception stackdump:

java.lang.NullPointerException
at GUI.makeFrame(GUI.java:71)
at GUI.<init>(GUI.java:28)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at bluej.runtime.ExecServer$3.run(ExecServer.java:808)
+3  A: 

There's nothing there that will cause a null pointer exception unless matchPlay is null or matchPlay.returnPL1GamesWon() throws a null pointer exception itself.

Update: Based on the fact that the exception is coming from GUI.makeFrame, I have to ask if you've actually got a graphic display? Is this a command line app, a Swing app, or an Applet? It looks like you're trying to create a JLabel without a graphics context.

Paul Tomblin
I think if matchPlay.returnPL1GamesWon() returns null, it will just print 'null', not throw an NullPointerException?
Brabster
Yes, what Brabster said. However, it's possible that matchPlay.returnPL1GamesWon() is itself throwing a NullPointerException.
Eddie
@Brabster, @Eddie, you're right. Fixed the wording.
Paul Tomblin
if i new how to use this site i wouldo post the error message exactly <stacktrace or whatever its called> however i did leave a comment above saying how it cant be possible
@Roberto, you should be able to edit your question - just click the "edit" button below it.
Paul Tomblin
+3  A: 

Based on the information in the question: the reference matchPlay is null.

Updated: Given the info that matchPlay cannot be null, then the method that is called on matchPlay must be throwing the exception. Check the stack trace for the previous method call, should help to pinpoint the problem.

Brabster
it cant be tho becuase some of the other methods from matchPlay are working, i have the followingprivate Game matchPlay<constructor> matchPlay = new Game()so how can it be null?
Ah. You didn't say that. In that case, see @Paul Tomblin's answer below.
Brabster
A: 

i have managed to answer it,

it was the order of which i was assigning fields in the constructor

sorry for the bother

thanks everyone

Glad you figured it out!
Ascalonian