1

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
CodeGuy
  • 28,427
  • 76
  • 200
  • 317

2 Answers2

1

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.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
0

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.

Aubin
  • 14,617
  • 9
  • 61
  • 84
  • Nope, same thing....how do I have eclipse refresh the whole thing so that it cleans and builds so that resources will be in bin? – CodeGuy Feb 12 '13 at 22:32
  • And even if I manually put it in the bin, this still does not work unfortunately. Same problem, NullPointer... – CodeGuy Feb 12 '13 at 22:35
  • No, this does not work. I am running FROM ECLIPSE not from a Jar file. I need a solution that works for JAR and FROM ECLIPSE. – CodeGuy Feb 12 '13 at 22:44
  • I test it from Eclipse NOW! – Aubin Feb 12 '13 at 22:47
  • @CodeGuy as per [my answer](http://stackoverflow.com/a/14843166/592139) the correct path depends on exactly where you've put the files. Using `classLoader.getResourceAsStream("resources/myImage.gif")` would work if you put the file at `src/resources/myImage.gif`, etc. - if `myImage.gif` is directly inside `src` then you just need `"myImage.gif"` without the `resources/` – Ian Roberts Feb 12 '13 at 23:00