Skip to content
Advertisement

.jar File can’t find image file path

I’m creating a simple program that I now want to export as a executable jar file. Everything works fine except the jar file can’t find the image.

For creating the runnable JAR file I used the second option in Eclipse 2021-12 (Package required libraries into generated JAR). This seems to work well, because I only have the jar and no other folders I need to run the program.

My jar file structure looks like this:
jar_file/
├─ images/
│ ├─ frog.png

I’ve tried multiple ways of getting the image file.

This is how I define Icon:
private static Image icon;

Using toURI() and toString()

icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/frog.png").toURI().toString());

Eclipse

This does not work in Eclipse.

Path Output: file:/C:/Projekte/serviceticketapp/target/classes/images/frog.png

Jar File

This does not work in the Jar File.

Path Output: rsrc:images/frog.png

Using toExternalForm()

icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/frog.png").toExternalForm());

Eclipse

This does not work in Eclipse.

Path Output: file:/C:/Projekte/serviceticketapp/target/classes/images/frog.png

Jar File

This does not work in the Jar File.

Path Output: rsrc:images/frog.png

Using File and toURI()

File imageFile = new File(getClass().getResource("/images/frog.png").toURI()); icon = Toolkit.getDefaultToolkit().getImage(imageFile.getAbsolutePath());

Eclipse

This works in Eclipse.

Path Output: C:Projekteserviceticketapptargetclassesimagesfrog.png

Jar File

Throws error.

java.lang.IllegalArgumentException: URI is not hierarchical

Summary

Above you can see all the ways I tried to get the image file. Only one works in Eclipse and none of them work in the jar file.

What am I doing wrong or how do I have to arrange the files in order for it to work in the jar file and in Eclipse.

Please ask if you need more information. Thanks in advance.

Advertisement

Answer

I would use imagio (import javax.imageio.ImageIO)

tIcon = new TrayIcon(ImageIO.read(getClass().getResource("/images/frog.png"), "Service Ticket App");
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement