Chitika

Monday, September 27, 2004

using HTML in Swing components

I was going through the Sun tutorial on Swing this weekend. It's my second time since three years ago, when I use Swing last time. Many have changed since then, in fact the tutorial even states that there will be many enhancements in future versions, such as in JDK 5.0.

One of the few things that interest me is the ability to use HTML text formatting in Swing components. Here's an example:

button = new JButton(
  "<html><b><u>T</u>wo</b><br>lines</html>");

The text on this button will be displayed in two lines, where the first line consists of a 'T' which is bold & underlined, and 'wo' which is bold. You can even play with color, for example:

String color = null;
if (value <= 32) color = "blue";
else if (value <= 80) color = "green";
else color = "red";

StringBuffer sb = new StringBuffer ();
sb.append ("<html><font color=");
sb.append (color);
sb.append ('>');
sb.append (value);
sb.append ("</font></html>");

button.setText (sb.toString());

This will make our Swing application looks even more intuitive.

However, since HTML rendering involves many classes, it may be best to paint the HTML in a background thread prior to showing it.

Currently, the Swing components that supports HTML rendering are JButton, JLabel, JMenuItem, JMenu, JRadioButtonMenuItem, JCheckBoxMenuItem, JTabbedPane, JToolTip, JToggleButton, JCheckBox and JRadioButton.

I guess I'll be making intuitive suggestions if I were to create any Swing application in the future.. :D

Further Reading:
Swing Second Edition
Java Swing Second Edition

No comments:

Post a Comment