简体   繁体   中英

Null pointer exception JLabel

Why do I get a NullPointerException 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)

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.

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.

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

Change to:

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

Moreover then you can add Jlabel variable in public class if error occurred,

    public class YourClass{
             private JLabel player1CurrentScore;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM