HTML in Swing Widgets.

Although it is commonly known that the JEditorPane supports HTML, what most people do not know is that you can use HTML in every blessed Swing Text-Component. Yes, that includes JButtons, JLabel etc; and no, I am not pulling your leg. Now I am sure some guy would probably be thinking,

Khaib! This damned fool is pulling ma’ leg! I tried the bold and italic tag thingy and it don’ work! Yallah Gum!…

Well, if you only use something like:

/* ===INCORRECT=== */
JLabel m = new JLabel("<i>I'm a hopeless idiot!</i>");

It most definitely won’t work. Why? Because the widget will not know if you want it to use HTML or to just type an “i” between to “” signs. The simplest way to inform the widget that you want it to render HTML is to enclose the text in “html” tags. For example:

/*===CORRECT===*/
JLabel m = new JLabel("<html><i>I'm an html rendered idiot!</i></html>");

A Point to be noted is that when I say it can render HTML, I mean it can render every damn HTML structure. e.g it can render line breaks and horizontal rules.

String str = "<html>Line One<br/><b>Line Two</b><hr/>Rule!</html>";
JButton mybtn = new JButton(str);

screenshot:

HTML rendered widget

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s