dedalo
dedalo

Reputation: 2561

Java: setting an icon in a jar application

I've developed an application that I export into a runnable jar (including the libraries it needs). Everything works fine.

When running the app from Eclipse I'm able to change the icon that the application window shows:

BufferedImage image = null;
try {
   image = ImageIO.read(this.getClass().getResource("AT42.png"));
} catch (IOException e) {e.printStackTrace();}
this.setIconImage(image);   

The picture is placed in my .class files directory.

When I run it from Eclipse it shows the icon, but when I create a runnable jar and execute it I get the following exception:

Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.IllegalArgumentException: input == null!
        at javax.imageio.ImageIO.read(Unknown Source)
        at com.tools.at4.UserInterface.<init>(UserInterface.java:43)
        at com.tools.at4.GeneradorInformes.main(GeneradorInformes.java:8)
        ... 5 more

I guess the icon is not include in the jar file, my question is, is there any way of incluiding it, so that when I run the jar file the windows that are created show my icon instead of the Java cup?

Thanks!!

Upvotes: 2

Views: 3833

Answers (2)

dedalo
dedalo

Reputation: 2561

If I put the file where the .class files are I should modify my code like this:

image = ImageIO.read(this.getClass().getResource("/AT42.png"));

Thanks!!

Upvotes: 0

Michael
Michael

Reputation: 2726

With the path you are using your image needs to be put at the root of your jar file. Assuming you have your image in a directory in your project called "images", this ANT task would put the image(s) at the root of your jar:

<target name="construct-jar" depends="compile,javadoc">
    <copy todir="${build.dir}">
        <fileset dir="images"/>
    </copy>
    <jar destfile="${dist.dir}/${jar.name}" basedir="${build.dir}"/>
</target>

Upvotes: 1

Related Questions