Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: Displaying images from within a Jar

When running a Java app from eclipse my ImageIcon shows up just fine.

But after creating a jar the path to the image obviously gets screwed up.

Is there a way to extract an image from the jar at runtime so I can then open it up? Or, is there a better way to do this?

I'd like to distribute a single jar file if possible.

like image 448
jjnguy Avatar asked Aug 27 '08 20:08

jjnguy


1 Answers

To create an ImageIcon from an image file within the same jars your code is loaded:

new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg")) 

Class.getResource returns a URL of a resource (or null!). ImageIcon has a constructors that load from a URL.

To construct a URL for a resource in a jar not on your "classpath", see the documentation for java.net.JarURLConnection.

like image 101
Tom Hawtin - tackline Avatar answered Oct 21 '22 23:10

Tom Hawtin - tackline