Using HTML in Java Swing Controls

Have you ever wanted to provide text formatting in a Swing control? Have you ever wanted to have multiple lines of text in a tab? This Java tutorial will show you how to use the simplicity of HTML to provide flexible and powerful text formatting in Swing controls.

With Swing controls, you can use the setFont() and setColor() methods to specify the text font and color of the text in a Swing control. If you want to mix the font formatting or color of the text within the control, you might think you will need to extend the class and render the control yourself. There is no need to create a custom control to render it. You can simply use HTML to provide mixed formatting in a single control.

The first example formats each label of the tab with a different style. Within each tab, it will contain two styles of text.

//Create a tab with a bold label
tabbedPane.add("<html><b>Bold</b>Tab</html>", new JPanel());

//Create a tab with a italic label
tabbedPane.add("<html><i>Italic</i>Tab</html>", new JPanel());

//Create a tab with an underline label
tabbedPane.add("<html><u>Underline</u>Tab</html>", new JPanel());
The results of HTML formatting in the tabs:



You'll notice that each tab shows stylized text (bold, italic, and underline) and plain text. By simply inserting the <html> tags at the beggining and end of the text, it tells Swing that the label will contain HTML. Without the <html> tags, the html would be displayed as literal text. To format the text as bold, the <b></b> tags were placed around the text. To format the text as italic, the <i></i> tags were placed around the text. To underline the text, the <u></u> tags were placed around the text.

Next, we will create a multi-line tab by simply using the HTML <br> tag.
//Create a tab two lines of text
tabbedPane.add("<html>line 1<br>line 2</html>", new
JPanel());

The results of HTML formatting in the tabs:



In our example, the third tab has multiple lines of text. This was accomplished by simply inserting the <br> tag to cause a line break.

This tutorial only scratches the surface on what you can do with HTML in a Swing control. Try thinking outside the box and experiment with different HTML. There are a large number of possibilities. Here are some fun things to try:
  1. Try using HTML in a JToolTip to provide rich text formatting of tooltips.
  2. Use the <img> tag to include one or image within the control.
  3. Use tables to provide customized text layouts


0 comments:

Post a Comment