Using image resources in a jar using maven

2019-09-15 16:26发布

问题:

I have a java/maven project that uses tango icons, so I'm using the following dependency:

<dependency>
    <groupId>org.freedesktop.tango</groupId>
    <artifactId>tango-icon-theme</artifactId>
    <version>0.8.90</version>
</dependency>

And the following code, which would work ok before I moved the proyect to maven:

imageIcon = new ImageIcon(this.getClass().getResource(org/freedesktop/tango/22x22/actions/address-book-new.png));

However, it now results in NullPointerException for some reason. The generated jar does not contain the images, nor reference them in any way, but classes in other jars are.

I've investigated a lot, but I've found most people bundle their images with their source. This isn't my case.

What do I need to do for maven to reference and/or package these images propertly? How can I get maven to build a standalone runnable jar (this is a swing application).

回答1:

If you add a slash before the path it works:

ImageIcon imageIcon = new ImageIcon(this.getClass().getResource("/org/freedesktop/tango/22x22/actions/address-book-new.png"));

From the API:

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'. Otherwise, the absolute name is of the following form:
modified_package_name/name Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').