Here is my current directory structure (contained inside a connect4
directory):
├── pom.xml
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── dv
│ │ │ └── app
│ │ │ ├── App.java
│ │ │ ├── Board.java
│ │ │
| | |
│ │ │
│ │ └── resources
│ │ ├── red-chip.png
│ │
│ └── test
│ ...
|
└── target
├── classes/com/dv/app/*.class
Essentially from Board.java
, I am trying to access red-chip.png
.
I tried many variations for this to work, right now I just have:
ImageIcon redChip = new ImageIcon("red-chip.png");
I tried changing up the path to use /resources
, used the getResource
function, but nothing seemed to work.
When I generate the jar using mvn package
and run the jar file, it does not show the image.
I perform unzip -l <jar file>
and see that my red-chip.png has been moved to the root directory for some reason.
Length Date Time Name
--------- ---------- ----- ----
126 2019-05-30 20:03 META-INF/MANIFEST.MF
0 2019-05-30 20:03 META-INF/
0 2019-05-30 19:19 com/
0 2019-05-30 19:19 com/dv/
0 2019-05-30 19:20 com/dv/app/
0 2019-05-30 20:03 META-INF/maven/
0 2019-05-30 20:03 META-INF/maven/com.dv.app/
0 2019-05-30 20:03 META-INF/maven/com.dv.app/connect4/
4190 2019-05-30 19:20 com/dv/app/App.class
4975 2019-05-30 19:20 com/dv/app/Board.class
110 2019-05-29 20:29 META-INF/maven/com.dv.app/connect4/pom.properties
7856 2019-05-30 19:32 red-chip.png
Here is my pom.xml
. Main thing to look at is the build jar plugin.
(removed useless stuff like artifactID, etc)
<project xmlns="...">
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.dv.app.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
So my questions are as follows:
What is the proper way to reference my png file so it will be visible in the jar?
Why was the png file located in the root in the jar?
If you need to load image as an icon for application your code should be like this. This will set the icon for your application.
this.setIconImage(new ImageIcon(getClass().getResource("/red-chip.png")).getImage());
If you need to use setIcon
method, you can use
ImageIcon IC = new ImageIcon(getClass().getResource("/red-chip.png"));