Load image from resources in Maven

by GarciaPL on Saturday 14 March 2015

I would like to share a very useful snippet of code which allows you to load image located in resources folder (we talk about project in Maven). I assume that you know how looks project in Maven. For the record it is something like this :

Maven project structure

In one of my projects there was a need to store images inside in Swing application in .png and .gif format in resources directory (/src/main/resources/). At this moment I place those images manually, but in some near future I will use some library for instance JarPlug or MyJarExplorer to manipulate content of this jar file to automate this process.


Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/dvlogo.png"));
if (image != null) {
   ImageIcon icon = new ImageIcon(image);
   getMainLogo().setIcon(icon);
}
Above code retrieves image using Toolkit class from Maven's resources directory and create ImageIcon object which is used next in some JFrame to display it. Reference :  [1] Pastebin Source Code