JButton Label Example

JButton Label Example Note: It is advised to read Java JFC Swing Introduction and Swing Overview before reading this.

In the following program on JButton Label Example, the label is given different fonts and colors using HTML.

import javax.swing.*;  		
import java.awt.*;  		
import java.awt.event.* ;  	

public class JButtonDemo4 extends JFrame
  public JButtonDemo4()
    Container c = getContentPane();
    c.setLayout(new FlowLayout( )) ;
                                    // button label with single color
    JButton btn1 = new JButton("  My Button  ");

                                   // button label with two color: My in blue and Button in red color
    JButton btn2 = new JButton("  My   Button  ");
                             // following statement closes the window
    addWindowListener( new WindowAdapter()
      public void windowClosing(WindowEvent e)
    } ) ;
    setTitle("Learning JButton");
  public static void main( String args[ ] )
    new JButtonDemo4();

JButton Label Example
Output screenshot on JButton Label Example

Observe the following code on JButton Label Example:

JButton btn2 = new JButton("<html> <font size = 12 color = blue> My </font> <font size=12 color = red> Button </font> </html>");

In the above statement, the button label is given different fonts and colors(half the button one color and the other half in another color) which is not possible with AWT.

JFrame is closed using anonymous inner class of WindowAdapter.

Leave a Comment

Your email address will not be published.