Search code examples
javaswingjarexecutable-jarembedded-resource

Can I have my entire application in a single JAR file?


I don't quite understand how creation of a Swing application really works. I have created a simple application that gets a background image from a path.

ImageIcon imageIcon = new ImageIcon("C:\\Java\\ApplicationName\\out\\Resourses\\backGround.jpg");
Image image = imageIcon.getImage(); // Создание картинки из него
Image temp = image.getScaledInstance(500,500,Image.SCALE_SMOOTH); 
imageIcon = new ImageIcon(temp);
g2d.drawImage(temp,0,0,null);

It works, so I decided to make a JAR file independent from changes in the Java folder (like deleting this image) and put images in src - images ( package ). I don't know if it is possible though.

I started to get background image like this.

ImageIcon imageIcon = new  ImageIcon(this.getClass().getResource("/images/backGround.jpg")); 

The program works perfectly in IntelliJ IDEA but if I extract it to JAR file I get a blank background screen. Why is that?

And can I have my entire application including images in a single JAR file? One that is not dependent on other folders?


Solution

  • You can certainly put the image and the code in a single jar file. The image is not loading either because it's not in the jar file, or because it's not at the path /images/backGround.jpg inside the jar.

    One helpful thing about jar files that you may not know: they are in .zip format, so you can use any zip tool to see what is inside the jar (temporarily renaming the jar file to .zip might make this easier). IF the image is not there, fix your jar build (you didn't say how you are making it, so not sure what you need to change). If the image is there but under a different path, then fix the jar build to put it in the right place, or change the path you are reading it from.