Java Reference
In-Depth Information
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 JLa-
belHTMLDemo just puts up a JLabel formatted using this Java code:
public
public class
class JLabelHTMLDemo
JLabelHTMLDemo extends
extends JFrame {
/** Construct the object including its GUI */
public
public JLabelHTMLDemo () {
super
super ( "JLabelHTMLDemo" );
Container cp = getContentPane ();
JButton component = new
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>" );
component . addActionListener ( new
new ActionListener () {
public
public void
void actionPerformed ( ActionEvent evt ) {
System . out . println ( "Thank you!" );
}
});
cp . add ( BorderLayout . CENTER , component );
setSize ( 200 , 400 );
setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
}
public
public static
static void
void main ( String [] args ) {
new
new JLabelHTMLDemo (). setVisible ( true
true );
}
}
Figure 14-12 shows the program in operation.
Search WWH ::




Custom Search