Liakos Liakos - 5 months ago 15
Java Question

Loading images in the exported .jar file

So I started making this Java game and everything worked fine, except when I tried to export it as a runnable jar. It shows me a blank screen when I try to execute it. I found out that it has to do with the way I'm accessing the images so I tried to change the code according to what i read on here but it's still not working :[

I'm currently accessing the images through:

Image image;
image = ImageIO.read(getClass().getResource("/imageName"));


Maybe you guys can help me, would be great!

This is my package tree:

enter image description here

Answer

In order to include your resources inside your exported jar, they need to reside within the src folder (otherwise, it'll look for them in the current directory where the jar is run which is susceptible to change and would need to be supplied separately, which doesn't sound like what you want).

Meaning something like:

- src
  + com.liakos.SpaceShooter
  - res
    - 1.png
    - 2.png

And so on.

Then you can access it through the getResource API, i.e.:

Image image;
image = ImageIO.read(getClass().getResource("res/1.png"));