NullPointerException when parsing URL to ImageIcon
I am following few tutorials on JMonkey2.1
When I run those tutorials I get NullPointerExceptions where new ImageIcons are loaded using java.net.URL.
// 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);
But when I parse file path as a string instead of reading them as java.net.URL they work fine.
e.g: new ImageIcon("path/to/file")
This is the stack trace
Jun 4, 2011 4:18:2开发者_JS百科2 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.
What might be the reason for this? Thank you..
In order to use ClassLoader#getResource()
, the resource needs to be in the classpath.
When it's located in the same package as Lesson3
class, then do so
new ImageIcon(Lesson3.class.getResource("image.png"));
When it's located in a different package, then use an absolute path from the classpath root on, i.e. start with /
.
new ImageIcon(Lesson3.class.getResource("/com/example/image.png"));
This expects the file image.png
to be in the package com.example
.
Using new File()
is not recommended for relative paths as it depends on the current working directory which in turn depends on the way how you started the application which is not controllable from inside the application.
If you are trying to get path files relative to your class and getclass().get recourse does not work, use a File. Make a fie with the name with the image and use new imageIcon(file.getAbsoltuePath);
I cant really show you an example because I'm on my iPad.
精彩评论