解析到ImageIcon的URL时出现NullPointerException

Nir*_*han 2 java file-io nullpointerexception

我正在关注JMonkey2.1的一些教程

当我运行这些教程时,我得到NullPointerExceptions,其中使用java.net.URL加载新的ImageIcons.

// generate a terrain texture with 3 textures
ProceduralTextureGenerator pt = new ProceduralTextureGenerator(heightMap);
pt.addTexture(new ImageIcon(Lesson3.class.getClassLoader().getResource("path/to/file")), -128, 0, 128); //line 199
pt.addTexture(new ImageIcon(Lesson3.class.getClassLoader().getResource("dirt.jpg")), 0, 128, 255);
pt.addTexture(new ImageIcon(Lesson3.class.getClassLoader().getResource("highest.jpg")), 128, 255, 384);
pt.createTexture(32);
Run Code Online (Sandbox Code Playgroud)

但是当我将文件路径解析为字符串而不是将它们作为java.net.URL读取时,它们工作正常.

例如: new ImageIcon("path/to/file")

这是堆栈跟踪

Jun 4, 2011 4:18:22 PM class jme.test.Lesson3 start()
SEVERE: Exception in game loop
java.lang.NullPointerException
at javax.swing.ImageIcon.(ImageIcon.java:167)
at jme.test.Lesson3.buildTerrain(Lesson3.java:199)
at jme.test.Lesson3.initGame(Lesson3.java:151)
at com.jme.app.BaseGame.start(BaseGame.java:74)
at jme.test.Lesson3.main(Lesson3.java:62)
at jme.test.Main.main(Main.java:14)
Jun 4, 2011 4:18:22 PM com.jme.app.BaseGame start
INFO: Application ending.
Run Code Online (Sandbox Code Playgroud)

可能是什么原因?谢谢..

Bal*_*usC 5

为了使用ClassLoader#getResource(),资源需要在类路径中.

如果它与类位于同一个包中Lesson3,那么就这样做

new ImageIcon(Lesson3.class.getResource("image.png"));
Run Code Online (Sandbox Code Playgroud)

当它位于不同的包中时,则使用类路径根中的绝对路径,即以...开头/.

new ImageIcon(Lesson3.class.getResource("/com/example/image.png"));
Run Code Online (Sandbox Code Playgroud)

这要求文件image.png在包中com.example.

使用new File()不建议使用相对路径,因为它取决于这又取决于你的方式是如何开始这是不是从应用程序内部控制应用程序的当前工作目录.