HTML Text in Buttons and Labels

A neat feature of Swing is that it can interpret HTML-formatted text in JLabel and JButton labels. The following example shows how to create a button with some HTML-formatted text:

 JButton button = new JButton(
 "<html>"
 + "S<font size=-1>MALL<font size=+0> "
 + "C<font size=-1>APITALS");


Older versions of Java may not render complex HTML very well. But as of JDK 1.4, most basic HTML features are supported, including crazy things such as images and tables. Screenshot-1 uses an HTML table to arrange its text.

Screenshot-1. Button using HTML table
Java ScreenShot

Screenshot-2 uses an HTML image tag to display an image.

Screenshot-2. Button using HTML img tag
Java ScreenShot

The code for the two figures looks like this:

 String html=
 "<html><table border=1>"
 +"<tr><td>One</td><td>Two</td></tr>"
 +"<tr><td>Three</td><td>Four</td></tr>"
 +"</table>";
 JButton button = new JButton(html);
 String html2=
 "<html><h3>Learning Java</h3>"
 +"<img src=\"http://www.oracle.com/catalog/covers/learnjava3.s.gif\">";
 Jbutton button2 = new JButton(html2);


Comments