Java Applet getImage提供空指针异常

时间:2013-06-27 17:53:23

标签: java image applet nullpointerexception

我正在用Java制作基于applet的游戏,但我遇到了一个问题。我正在使用以下堆栈跟踪获得空指针异常:

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)

ImageEntity.java第84行的代码如下:

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

使用测试打印,applet不为空,也不是getURL( filename )

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

为什么我得到空指针异常?

1 个答案:

答案 0 :(得分:2)

以下是java.applet.Applet.getAppletContext(Applet.java:204)的代码:

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

'stub'为空。 AppletPanel.runLoader()拨打setStub()

您的代码在Applet有机会初始化之前调用getImage(即存根仍然为空)。

在init()方法中调用getImage()。不要在构造函数中或在字段初始化期间调用它。