Here we are going to work with the most useful component in Java Swing JLabel.

Swing JLabel :

We can display a small text using JLabel component in Swing.

Simple JLabel Demo :

LabelDemo.java
package com.swing.examples;

import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class LabelDemo extends JFrame {

    JLabel label;
    Container container;

    LabelDemo() {
        super("My JLabel Demo");
        label = new JLabel("Hello World!");
        container = getContentPane();
        container.add(label);
        setSize(200, 200);
        setVisible(true);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        new LabelDemo();
    }
}

JLabel with html content :

We can apply the html elements while using JLabel component.

LabelDemo.java
package com.swing.examples;

import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class LabelDemo extends JFrame {

    JLabel label;
    Container container;

    LabelDemo() {
        super("My JLabel Demo");
        label = new JLabel("Hello World");
        container = getContentPane();
        container.add(label);
        setSize(200, 200);
        setVisible(true);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        new LabelDemo();
    }
} 

 

JLabel with images :

We can use the images as JLabel.

JLabel.java
package com.swing.examples;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class LabelDemo extends JFrame {

    JLabel label;
    ImageIcon icon;

    Container container;

    LabelDemo() {
        super("My JLabel Demo");
        icon = new ImageIcon("C:\\images\\dukeWave.gif"); // Your Images path
        label = new JLabel("Hello World !", icon, SwingConstants.LEFT);

        container = getContentPane(); // new ContentPane();

        container.setLayout(new FlowLayout());

        container.add(label);

        setSize(300, 200);

        setVisible(true);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }

    public static void main(String[] args) {
        new LabelDemo();
    }
}


Happy Learning 🙂