Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading ImageIcon from JAR or file system

I have a simple program that needs to display images. I know how to do this running the code from Eclipse and I know how to do it running from a JAR file, but I'd like a solution that works in both cases.

Eclipse project is as such:

- Project (java)
  - src
    - controller
      - Main.java
    - ui
      - Display.java
  - images
    - image.jpg

The code snippet that works from within Eclipse:

ImageIcon image = new ImageIcon("images/image.jpg);

The one that works for a JAR (all in a single JAR file):

java.net.URL imgURL = getClass().getResource("/images/image.jpg");
ImageIcon image = new ImageIcon(imgURL);

What would I need to change in order to get a single piece of code that works in both situations?

like image 387
Martijn Avatar asked Jan 15 '12 15:01

Martijn


1 Answers

Put the images folder inside the src folder, and Eclipse will copy the images into the target folder (bin or classes, generally), which will make them available from the classpath, just as if they were in your jar in the released version of your app.

getResource() doesn't look in a jar. It looks in the classpath of the classloader. Whether the image is in a jar or not is thus not important. It must be in the classpath. And obviously the target folder of eclipse (bin or classes, generally) is in the runtime classpath of the app when you launch it from Eclipse.

like image 137
JB Nizet Avatar answered Oct 18 '22 17:10

JB Nizet