JLabel空指针异常
当我尝试在标签上运行此命令时,为什么会出现 NullPointerException:
JLabel player1CurrentScore = new JLabel("" + matchPlay.returnPL1GamesWon(),
JLabel.CENTER);
是因为我不能像这样连接两个字符串吗?
理想情况下,我尝试将标签设置为玩家的分数,以便可以在需要时正确递增。
这是我的异常堆栈转储:
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据问题中的信息:参考 matchPlay 为空。
更新:鉴于 matchPlay 不能为 null 的信息,则在 matchPlay 上调用的方法必须抛出异常。 检查先前方法调用的堆栈跟踪,应该有助于查明问题。
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.
除非 matchPlay 为 null 或 matchPlay.returnPL1GamesWon() 本身引发空指针异常,否则没有任何内容会导致空指针异常。
更新:基于异常来自GUI.makeFrame的事实,我不得不问你是否真的有图形显示? 这是命令行应用程序、Swing 应用程序还是 Applet? 看起来您正在尝试创建一个没有图形上下文的 JLabel。
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.
更改为:
此外,如果发生错误,您可以在公共类中添加 Jlabel 变量,
Change to:
Moreover then you can add Jlabel variable in public class if error occurred,
我已经设法回答这个问题,
这是我在构造函数中分配字段的顺序,
抱歉打扰,
谢谢大家
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