Styling Java Buttons & Labels with HTML tags

Introduction:

Java buttons and labels support using different HTML (Hyper Text Markup Language) tags. HTML is Web page development language where as Java is Programming language but still Java executes the HTML tags and displays the output according to the HTML tags. These tags can be used to insert new line on the button or labels or styling the text on the buttons and labels. Text Area does not support executing HTML tags it displays the tags as it is. Buttons and label support following HTML tags.

Tags Supported by Labels and Buttons

1. List tags <li>,<ol>,<ul> tags. These tags are used for creating ordered or unordered list. 2. Physical Style tags like <b>, <br>, <i>,<s>, <sub>,<sup>, etc These tags are for styling the text. We can subscript and superscript certain text on button and labels. 3. <table> tag Data in the form of rows and columns can be displayed on labels using <table> tag. Display of images using <img> tag is not supported.

Demo:

Following is the example of using HTML tags on Buttons and labels. Text to be displayed must be enclosed in <html> tags when <html> style is to be applied. Ending <html> tag is not compulsory. Following Program displays table, list on JLabel and physical style tags on button. Here two panels are created upperPanel and lowerPanel and Labels and buttons are added to these panels. Then panels are added to frame using Grid Layout. border attribute of table is set to 1 so that border of 1 pixel is drawn around the table. <tr> represents start of the row, <th> tag is used for inserting table heading and <td> tag is used to insert normal data. <ul> stands for Unordered list. It displays data in the form of list using bullets.<li> list the individual list item. <br> inserts a new line.
  1. String text1;
  2. JLabel table;
  3. JPanel upperPanel=new JPanel();
  4. JPanel lowerPanel=new JPanel();
  5. text1="<html> <table border=1><tr><th>Programming Language</th><th> Developed By</th></tr><tr><td>C</td><td>Dennis Richie</td></tr><tr><td>C++</td><td>BJourne Stroustrup</td></tr><tr><td>Java</td><td>AT & T lab</td></tr></table>";
  6. String text3="<html><b>Programming Languages</b><br><ul><li>Java<li>C<li>C++<li>C#</ul>";
  7. JLabel list=new JLabel(text3);
  8. table=new JLabel(text1);
  9. String text2="<html><b>bold</b> and <i>Italic</i>";
  10. JButton button2=new JButton(text2);
  11. JButton button3=new JButton("<html>Hot Cup of<br><h4>Java</h4></html>");
  12.  
  13. this.setLayout(new GridLayout(0,1));
  14. this.add(upperPanel);
  15. this.add(lowerPanel);
  16. upperPanel.add(table);
  17. upperPanel.add(list);
  18. lowerPanel.add(button3);
  19. lowerPanel.add(button2);
  20.  
  21. this.setSize(600,250);
  22. this.setVisible(true);
  23. this.setDefaultCloseOperation(EXIT_ON_CLOSE);
This HTML tags can be used to style the content of Label and buttons in Java. Complete program is attached below.

Add new comment