17

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?

Community
  • 1
  • 1
jedierikb
  • 12,752
  • 22
  • 95
  • 166

4 Answers4

16

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>") );
jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • Also, _don't forget to wrap the url in apostrophes_ (like me). Strangely enough, without apostrophes it worked in eclipse but not when bundled in a jar. – domids Sep 26 '17 at 09:38
9

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!

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
gotomanners
  • 7,808
  • 1
  • 24
  • 39
6

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

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Because even the original demo from Sun for using HTML in Swing does not embed the images in HTML (for generating buttons with image icons), I doubt that there is even support for displaying images in place. I remember reader "limited subset of HTML" somewhere, but can't find a reference right now.

Edit: Please see Andrew's comment and answer, it really works.

Waldheinz
  • 10,399
  • 3
  • 31
  • 61
  • "I doubt that there is even support for displaying images in place." While the `JEditorPane` will only display a limited sub-set of HTML with simple CSS - you are way off track there. See my example. – Andrew Thompson Jun 17 '11 at 01:50