Friday, October 31, 2008

Embedding image in a JLabel

Let's suppose you would like to embed an image inline to a JLabel, JRadioButton or other basic Swing component text (except JEditorPane or JTextPane - that would be cheating ;-))

Let's suppose you have your image on the classpath.

Swing supports HTML out of the box fairly well, so let's try this:
final String msg = "<html>Nice pic: <img src=\"hmmm....\">, is it?";
final JLabel label = new JLabel(msg);

Yeah, the image URL. It needs to point to the image on the classpath and it needs to be understood by Swing.
I considered a custom protocol for a while, but implementing one is cumbersome and an overkill actually.

Long story short:
final URL image = getClass().getResource("/images/image.png");
final String msg = "<html>Nice pic: <img src=\"" + image.toString()
+ "\">, isn't it?";
final JLabel label = new JLabel(msg);

This assumes that getResource() returns a meaningful URL and URL.toString() is reversible. Apparently it is - you get either a file: or jar: URL depending on how you packaged your app.

0 comments:

Post a Comment