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.
To practice Swing, Java's GUI toolkit, I created a simple program that only displayed an hourglass icon. 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 ");
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.
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. I did it
https://virtualwalk.hatenadiary.org/entry/20121013/1350127275 http://hiesuke.hatenablog.com/entry/2016/12/30/101639
Recommended Posts