header

JLabel Class

A label is a component used to display some text on the user interface; usually to identify (or label) some other component. The user cannot edit the text displayed on a label.

Normally, you can't see exactly how big a label is. In the images below, the background color has been changed so you can see the actual size of the JLabel component. By default, the size of a label is determined by the length of its text which is left-justified within the label:

Default Label

If a label is stretched horizontally, the text remains left-justified:

Stretched Label

Import

The JLabel class is imported by the statement:

import javax.swing.*;

Selected Constructors

JLabel()
JLabel(String text)
JLabel(String text, int horizontalAlignment)

The text parameter is a string variable or a literal string (enclosed by quotation marks) and specifies the text that is to appear on the label.

The horizontalAlignment parameter specifies the horizontal alignment of the label text (left-justified, centered, or right-justified). See the setHorizontalAlignment method below for the appropriate values for this parameter.

Selected Methods

setFont(Font f)

Set the font used to display the label to the specified font.

setHorizontalAlignment(int alignment)

Set the horizontal alignment of the label text to the specified value. This settings determines where the text is placed within the area allocated to the JLabel component. The alignment parameter can be any of the following constants (defined in the SwingConstants class):

Constant Effect Example
SwingConstants.LEFT Text is left-justified Left-Justified
SwingConstants.CENTER Text is centered Centered
SwingConstants.RIGHT Text is right-justified Right-Justified
setText(String text)

Set the label text to the specified value. This is the text that will be displayed on the JLabel component.

Example

The Java code below creates a label with the text, "This is a Label", in a plain, 12-point, serif font centered within the label:

JLabel lblExample;
lblExample = new JLabel("This is a Label");
lblExample.setHorizontalAlignment(SwingConstants.CENTER);
lblExample.setFont("Serif", Font.PLAIN, 12);

See also: Font