Java Documentation

JLabel: Displaying Text in Swing

JLabel is used to display a short piece of read-only text (or an icon) inside a Swing window. It is often paired with input components like buttons or text fields.

Example: JLabel with a Button

This example creates a label and a button in the same frame usingFlowLayout. The label gives a description and the button is an action the user can click.

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

class MyFrame extends JFrame {
    MyFrame() {
        setTitle("Components - JLabel");

        JLabel l1 = new JLabel("Click The Button:");
        JButton b1 = new JButton("Click here");

        add(l1);
        add(b1);

        setLayout(new FlowLayout());
        setSize(500, 500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

public class JLabelDemo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
Reference & full codeView on GitHub

What is JLabel?

A JLabel is a display-only component. It shows text or an icon, but the user cannot type into it. Labels are typically used to describe other components (like input fields or buttons).

  • Commonly used next to text fields or buttons as captions.
  • Can display plain text, HTML-formatted text, or images.
  • Does not accept input; it is purely for display.

Line-by-line: Understanding the JLabel example

The JFrame setup is the same pattern as before. Here we focus on how the label and button are created and added.

JLabel l1 = new JLabel("Click The Button:");
JButton b1 = new JButton("Click here");

Creates a label with instructional text and a button the user can click. These are two separate components.

add(l1);
add(b1);

Adds the label and the button to the frame's content area. The layout manager decides how they are positioned.

setLayout(new FlowLayout());

Uses FlowLayout, which arranges components in a row (left to right) similar to words in a sentence. As you resize the window, the components flow to the next line if needed.

Where JLabel fits in GUI design

Labels are small, but they make interfaces readable. You will useJLabel to name fields, describe buttons, and show messages to users in almost every real GUI program.