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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With