[JAVA] Include image resources in jar file

Image disappears when outputting jar file from IntelliJ

When I made a GUI tool using Swing, the image file was displayed properly when it was executed on IntelliJ, but I faced the problem that the image file could not be displayed properly when it was output as a jar file. When I googled, it seemed to be a well-known phenomenon, and a solution came out immediately. The following is a summary of the solution as a memo for myself.

Situation explanation

To practice Swing, Java's GUI toolkit, I created a simple program that only displayed an hourglass icon. スクリーンショット 2020-01-22 10.42.20.png Like this

The icon is named hourglass.png file and saved directly under the src folder. In addition, the reading of the icon file is described as follows. ImageIcon myIcon = new ImageIcon("hourglass.png "); スクリーンショット 2020-01-22 10.49.04.png

Running this code on IntelliJ will run the program with the hourglass icon properly displayed. However, when I output the jar file and execute the program from the terminal, the icon cannot be displayed as shown below.

スクリーンショット 2020-01-22 11.23.16.png

solution

Use ClassLoader.getResource ().

In Java, ClassLoader.getResource () is prepared as a process to acquire resource information such as files.

In the previous code, ʻImageIcon myIcon = new ImageIcon ("hourglass.png "); `


ClassLoader cl = this.getClass().getClassLoader();
ImageIcon myIcon = new ImageIcon(cl.getResource("hourglass.png "));

By rewriting as, even after outputting as a jar file, the image resource will be referenced properly, so the image will be displayed. スクリーンショット 2020-01-22 10.42.20.png I did it

Reference source

https://virtualwalk.hatenadiary.org/entry/20121013/1350127275 http://hiesuke.hatenablog.com/entry/2016/12/30/101639

Recommended Posts

Include image resources in jar file
Include image in jar file with java static method
Include image resources in jar file
Upload Rails app image file to S3
Image upload
How to add jar file in ScalaIDE
[Java] Read the file in src / main / resources
Include external jar in package with Spring boot2 + Maven3
Include the source code generated by Doma in the source JAR
Add an external jar file in your IntelliJ project.
[Java] Get the file in the jar regardless of the environment
How to debug the generated jar file in Eclipse
Create a jar file that can be executed in Gradle
Install yarn in docker image
I got stuck in File
What is a jar file?
JavaFX-Load Image in the background
Text file placed in resources in Java cannot be read when jarted
[Gradle] The story that the class file did not exist in the jar file
How to make a jar file with no dependencies in Maven
Add a time stamp to the JAR file name in Gradle