Java Cookbook, Second Edition

Problem

You want more control over the formatting of text in JLabel and friends.

Solution

Use HTML in the text of the component.

Discussion

The Swing components that display text, such as JLabel, format the text as HTML instead of as plain text if the first six characters are the obvious tag <html>. The program JLabelHTMLDemo just puts up a JLabel formatted using this Java code:

// Part of JLabelHTMLDemo.java JButton component = new JButton( "<html>" + "<body bgcolor='white'>" + "<h1><font color='red'>Welcome</font></h1>" + "<p>This button will be formatted according to the usual " + "HTML rules for formatting of paragraphs.</p>" + "</body></html>");

Figure 14-12 shows the program in operation.

Figure 14-12. JLabel with HTML text

Категории