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?
Put the
imagesfolder inside thesrcfolder, and Eclipse will copy the images into the target folder (binorclasses, 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 (binorclasses, generally) is in the runtime classpath of the app when you launch it from Eclipse.