Java programming course: 14.2 JLabel


JLabel

The JLabel class will show a read-only piece of text:

private JPanel buildUI() {
    JPanel panel = new JPanel(new BorderLayout());
        
    // Components will go here...
    JLabel label = new JLabel("This is a text label");
    panel.add(label);
        
    // Return the built panel
    return panel;
}
 

If you run the frame, you should see the following:

JLabel

By default, the text is left aligned, but you can optionally supply a second argument to the constructor to specify right or centre alignment:

JLabel label = new JLabel("This is a text label", JLabel.RIGHT); 

If you need to change the text that appears on the label you can invoke the setText() method:

label.setText("Some different text"); 

There is also a getText() method which returns the text to be displayed as a String.

If you want to show the label using a different font you can instantiate and assign a suitable Font object:

Font f = new Font("Serif", Font.BOLD, 22);
label.setFont(f);
 

The Font constructor accepts three argument values:

  • The name of the font you require
  • Whether the font should be plain, bold or italic (using the constants Font.PLAIN, Font.BOLD or Font.ITALIC respectively. If you want your font to be both bold and italic, you can separate the constants with a vertical bar, i.e., Font.BOLD|Font.ITALIC
  • The point size of the font

If you want the text to be shown in a particular colour you can assign a suitable Color object either through one of its colour constants or a colour combination you specify:

// Using a colour constant: available constants are
// BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GREY,
// MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW
label.setForeground(Color.RED);
        
// Using a red, green, blue combination
label.setForeground(new Color(100, 50, 210));
 

If you use the red, green, blue combination constructor then each value must be between 0 and 255 to indicate the amount of that colour that should be used. This allows you to obtain fine degrees of shading.



Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Thursday, 11 December 2025

Captcha Image