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 buttons. Following some instructions on the Internet, I created a “source” directory by clicking on the project. I named the source directory as “res” and moved my images to this directory.
public static ImageIcon getIcon() {
if (isThisJarfile()) {
URL url = this.class.getResources("/res/myicon.png");
return new ImageIcon(url);
}else {
return new ImageIcon("/res/myicon.png");
}
}
This works fine when the app is not packaged as a jar file (great for debugging). However, when maven packages it, I see that the images are put in the root directory of the jar file. The following call works:
URL url = this.class.getResource("/myicon.png");
I am wondering if there is some step that I overlooked.
Note that I didn’t have to do anything special to pom.xml for the images. Maven automatically picked them up (except that it is putting them in the wrong location).
Thank you in advance for your help.
Regards,
Peter
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 subdirectoryimages, so that the full path would besrc/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.
This function can be used as
getImage("images/some-image.png")in order to loadsome-image.pngfile in the image directory.If
ImageIconis required then simply callingnew ImageIcon(getImage("images/some-image.png"))would do the trick.