Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading images from jars for Swing HTML

While this answer works to load images from Jar files for ImageIcons, I cannot seem to get the right path for images referenced in Swing HTML.

This displays an image in the Swing HTML when the resources are not bundled into a jar:

new JLabel("<html><table cellpadding=0><tr><td><img src='file:icons/folder_link.png'></td></tr><tr><td>100</td></tr></table></html>") );

Inside of the jar, the image can be successfully referenced (and displayed) into an ImageIcon:

Icon topIcon = new ImageIcon( getClass().getResource("icons/folder_link.png" ) );

However, my attempt to use the getResource technique for Swing HTML doesn't work.

String p = getClass().getResource("icons/folder_link.png" ).getPath();
new JLabel("<html><table cellpadding=0><tr><td><img src='" + p + "'></td></tr><tr><td>100</td></tr></table></html>") );

What's the secret?

like image 962
jedierikb Avatar asked Jun 16 '11 14:06

jedierikb


3 Answers

Without actually having tried it, I would assume that the HTML renderer can access your image if you include the resource URL in your HTML code:

String p = getClass().getResource("icons/folder_link.png" ).toString();
new JLabel("<html><table cellpadding=0><tr><td><img src='" + p + "'></td></tr><tr><td>100</td></tr></table></html>") );
like image 87
jarnbjo Avatar answered Oct 14 '22 17:10

jarnbjo


URL is the secret

Try this mate:

URL p = getClass().getResource("icons/folder_link.png" );
new JLabel("<html><table cellpadding=0><tr><td><img src='" + p + "'></td></tr><tr><td>100</td></tr></table></html>") );

Then you could also do this:

Icon topIcon = new ImageIcon(p);

and then set this icon as the icon for your JLabel if you want to do that!

like image 9
gotomanners Avatar answered Oct 14 '22 17:10

gotomanners


Answer expanded and moved to Is it possible/how to embed and access HTML Files in a JAR?

like image 6
Andrew Thompson Avatar answered Oct 14 '22 18:10

Andrew Thompson