2

My program uses Image.class, which helps me recieve image.

Image img = new ImageIcon("Shooter2D/res/background.jpg").getImage();

When the program is run from the development environment - everything works, after compiling a jar file - does not work. Tell me how to properly set the path to work in the IDE (Intellij IDEA) and in the archive. Shooter2D.jar contain:

- META-INF
Manifest-Version: 1.0
Main-Class: Shooter2Dv22082013.Main
- res
all pictures
- Shooter2Dv22082013
all .class files, main is Main.class

indicative figure: http://imageshack.us/photo/my-images/801/eyjv.png/

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Eldar
  • 153
  • 5
  • 13
  • Try to use it as resource: [link](http://stackoverflow.com/questions/6845231/how-to-correctly-get-image-from-resources-folder-in-netbeans) – ahmedalkaff Aug 22 '13 at 11:58

1 Answers1

3

Here's what the javadoc says about the constructor of ImageIcon:

Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path.

(emphasis mine)

Your image is not stored in a file. It isn't in your file system. It's in a jar that is itself in the classpath. And that's where you want to load it from. Wherever the jar file of your application is on the end-user's machine, your program wants to load it from this jar file. And all the resources in this jar file are available from the ClassLoader.

So you should use

new ImageIcon(MyClass.class.getResource("/res/background.jpg"))

or

new ImageIcon(MyClass.class.getClassLoader().getResource("res/background.jpg"))
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Not sure but I think that you should add a `/` at the beginning of the second path also. – Arnaud Denoyelle Aug 22 '13 at 12:06
  • i said `Tell me how to properly set the path to work in the IDE (Intellij IDEA) and in the archive.` if i use .getResource, then i can't run my app in IDE(IDEA) it throws exception : NullPointerException – Eldar Aug 22 '13 at 12:09
  • @ArnaudDenoyelle: I'm sure it doesn't need one. – JB Nizet Aug 22 '13 at 12:20
  • @Eldar: that means that the `res` directory is not under your source directory, where it should be. Once it's there, IDEA will "compile" the images by copying them to the output directory, along with the .class files, and they will thus be part of the classpath. – JB Nizet Aug 22 '13 at 12:21
  • after your comment i moved my `res` to `Shooter2Dv22082013` directory. and now it's compiles right and works in IDEA good. thanks – Eldar Aug 22 '13 at 12:58