Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Images will not work in a .jar file

When a JAR of an application is created, the images in the application no longer appear. An example of our code for loading images is:

ImageIcon placeHolder = new ImageIcon("src\\Cards\\hidden.png");

We have no idea why this is happening. The application runs as expected if we do not compress it to a JAR; as a JAR, the images simply disappear. We also tried using URLs instead of ImageIcons, but that just causes the program not to run at all.

Any ideas?

EDIT: We are putting the image files into our JAR file in the correct paths, so that's not the problem.

like image 921
akbiggs Avatar asked Nov 20 '25 02:11

akbiggs


1 Answers

Check the API for the constructor you're calling. The string you pass in is a file path - when the resources are packaged in a JAR, there is no file on the filesystem containing the image, so you can't use this constructor any more.

Instead you'd need to load the resources from a stream, using the classloader, and pull them into a byte array:

byte[] buffer = new byte[IMAGE_MAX_SIZE];
InputStream imageStream = getClassLoader().getResourceAsStream("src\Cards\hidden.png");
imageStream.read(buffer, 0, IMAGE_MAX_SIZE);
ImageIcon placeHolder = new ImageIcon(buffer);

Needs more exception and edge-case handling, of course, but that's the gist of it.

like image 136
Andrzej Doyle Avatar answered Nov 22 '25 16:11

Andrzej Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!