I am trying to load icons from a jar file. I have both tried to load it from classes within the jar file as well as classes outside the jar file.
outside of the
Icon icon = new ImageIcon(ClassLoader.getSystemResource("icons/mouse.png"));
From the JavaDoc of getSystemResource()
:
Find a resource of the specified name from the search path used to load classes...
This will find your icons even in a jar-file.
final java.net.URL imageURL3 = com.java.html.LoadHTMLExample.class.getResource( "icons/" );
works for the below directory structure
myjar.jar | |- ... |- LoadHTMLExample.class |- ... -- icons | - mourse.png
Thanks for the help everyone
I think that getResource
gets the resource relative to the location of LoadHTMLExample.class
. So your jarfile
should be structured in the following way:
myjar.jar
|
|- ...
|- LoadHTMLExample.class
|- ...
\-- icons
|
\- mourse.png
Also, you might be getting stream through getResourceAsStream
than getting the URL
.
I've always used the system class loader, whose path is relative to the root of the JAR:
URL url = ClassLoader.getSystemClassLoader().getResource("icons/mouse.png");
Icon icon = new ImageIcon(url);
Is the jar in question on the classpath of your runtime? I have a jar with PNGs in it, and I can recreate the nulls if I don't include it on the classpath. If the jar is there they go away.
Skip the class loader, and get the resource as a stream instead. If you don't need the URL you can turn them directly into BufferedImages like so. I've left the stream and exception handling as a further exercise.
InputStream stream = LoadHTMLExample.class
.getResourceAsStream( "/icons/mouse.png" );
BufferedImage image = ImageIO.read( stream );
Questioner needs the URL which brings us back to everyone else's suggestions. The images are definitely in the jar aren't they?