Home » Java » netbeans – Java excluding images when building jar file-Exceptionshub

netbeans – Java excluding images when building jar file-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I made a project with a GUI in Netbeans. The GUI has a label called GIFL2 which loads an image when a button is pressed, via

GIFL2.setText("");
GIFL2.setIcon(new ImageIcon("src/torrehanoirecursion/" + path));

This works just fine in Netbeans when I run the code inside. It does load the image successfully.

Problem is, when I build the project and I open the jar file, the images don’t load.
I initially thought it was because the images were inside an img folder, which was in turn inside of src. So the relative path for the folder was src/torrehanoirecursion/img

However, I moved all of the images to src itself, with no folder, because I read that java could be excluding them for not being part of src, but it still doesn’t work. No errors or anything, it simply doesn’t load them into the jar.

I went to project > properties > packaging. “Copy dependent libraries” is checked,
“build jar on compile” is checked, “compress jar” is unchecked, and “exclude from jar” is completely empty.

Any ideas as to what might be happening?

How to&Answers:

If you use Maven you should put all resources you want to include on target jar under src/main/resources directory on your project:

pom.xml
src/main/java
src/main/java/resources
src/main/java/resources/img1

You can also include files under different directories as for example src/other-resources. This case on your pom.xml you should set these paths under build section as follow:

<build>
    <resources>
        <resource>
            <directory>src/other-resources</directory>
        </resource>
    </resources>
</build>

For more details see at Maven resources plugin documentation: https://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html


Update: Solution with not Maven project via Netbeans

As you specified you’re project is not managed with Maven I reported steps that could allow you to solve with Netbeans.

  1. Create a resources directory on root path of your project
  2. Open your project properties on Netbeans IDE and select Sourceson categories section
  3. Add the resources folder on Source package folder section

Then target jar should contain all files under resources directory on classpath.


Update: Manually inject resources on target jar

At the end you can also inject the whole src/main/java/resources directory on your target jar manually with the following command after the build ( you should automate this at least with a bash script or specific task on Netbeans ):

cd src/main/java/
jar uf project.jar resources