Folks,
I am developing a Java application using Eclipse. Maven is used to create the final jar file.
In the application, I use some image icons for the butto
If you're following the standard Maven project directory structure then it is best to put all non-Java resources under src/main/resources
. For example, you could create a subdirectory images
, so that the full path would be src/main/resources/images
. This directory would contain all your application images.
A special care should be taken to properly access images when application is packaged. For example, the following function should do everything you need.
public static Image getImage(final String pathAndFileName) {
final URL url = Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
return Toolkit.getDefaultToolkit().getImage(url);
}
This function can be used as getImage("images/some-image.png")
in order to load some-image.png
file in the image directory.
If ImageIcon
is required then simply calling new ImageIcon(getImage("images/some-image.png"))
would do the trick.
Take a look at maven resources plugin
I had my favicon in the root of maven project and it was not getting included in the generated war. With lot of googling I got the solution from maven help page.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<webResources>
<resource>
<directory>${project.basedir}</directory>
<!-- the list has a default value of ** -->
<includes>
<include>favicon.ico</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>