简体   繁体   English

Java Applet getImage提供空指针异常

[英]Java Applet getImage gives null pointer exception

I'm making an applet based game in Java, but I'm running into a problem. 我正在用Java制作一个基于applet的游戏,但我遇到了一个问题。 I'm getting a null pointer exception with the following stack trace: 我正在使用以下堆栈跟踪获得空指针异常:

at java.applet.Applet.getAppletContext(Applet.java:204)
at java.applet.Applet.getImage(Applet.java:274)
at ImageEntity.load(ImageEntity.java:84) <==lowest code written by me
at SpriteTest.<init>(SpriteTest.java:14)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:374)
at java.lang.Class.newInstance(Class.java:327)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:795)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:724)
at sun.applet.AppletPanel.run(AppletPanel.java:380)
at java.lang.Thread.run(Thread.java:722)

The code at ImageEntity.java line 84 is as follows: ImageEntity.java第84行的代码如下:

image = applet.getImage( getURL( filename ) );

Using a test print, applet isn't null, nor is getURL( filename ) . 使用测试打印, applet不为null,也不是getURL( filename )

Printing getUrl( filename ) returns file:/home/glenn/Documents/code/RMGame/RMPatrolGame/house7.gif . 打印getUrl( filename )返回file:/home/glenn/Documents/code/RMGame/RMPatrolGame/house7.gif

Why am I getting a null pointer exception? 为什么我得到空指针异常?

Here is the code for java.applet.Applet.getAppletContext(Applet.java:204): 以下是java.applet.Applet.getAppletContext(Applet.java:204)的代码:

public AppletContext getAppletContext() {
    return stub.getAppletContext();
}

'stub' is null. 'stub'为空。 AppletPanel.runLoader() calls setStub() . AppletPanel.runLoader()调用setStub() 。

Your code is calling getImage before the Applet has had a chance to initialize (ie stub is still null). 您的代码在Applet有机会初始化之前调用getImage (即存根仍为空)。

Call getImage() in the init() method. 在init()方法中调用getImage() Do not call it in a constructor or during field initialization. 不要在构造函数中或在字段初始化期间调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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