CodeGuy
CodeGuy

Reputation: 28905

Using an image in a JAR file

I can't seem to get this right...

I have a Java project in Eclipse called MyProject. In its root is the folders bin, src, and resources. Inside of resources, I have an image named myImage.gif.

In my code, I want to use this image, and I want it to work whether or not this is running from a Jar file. I currently am doing this

ImageIcon j = new ImageIcon(getClass().getResource("/resources/myImage.gif"));

but it is spitting out a null when I run it through Eclipse (not as a Jar).

What is the right way to do this?

Upvotes: 1

Views: 229

Answers (2)

Aubin
Aubin

Reputation: 14883

Place resources into src and Eclipse will copy it into bin.

ImageIcon ii =
   new ImageIcon(
      ImageIO.read(
         getClass().getClassLoader().getResourceAsStream(
            "resources/myImage.gif" )));

Without / before the path.

Upvotes: 0

Ian Roberts
Ian Roberts

Reputation: 122424

If you were to tell Eclipse to treat resources as a source folder then you should be able to say

ImageIcon j = new ImageIcon(getClass().getResource("/myImage.gif"));

When you come to build the JAR you'll have to ensure that the contents of the resources directory go into the top level of the JAR file in order for the same path to work in the JAR case, i.e.

META-INF
  MANIFEST.MF
com
  example
    MyClass.class
myImage.gif

Alternatively, and probably the more common Java idiom, put the image file in the same directory as the .java file (src/com/example in this case) and then use getResource without the leading slash

new ImageIcon(getClass().getResource("myImage.gif"));

Class.getResource resolves a relative path like that against the package of the class in question. Again, you need to have the same structure in the JAR when you come to build that, this time with myImage.gif under com/example.

Upvotes: 1

Related Questions