How do I format JLabel using HTML?

JLabel text can be formatted using an HTML standard tags. The example below shows you how we can use and HTML font tag to change the font size, color and style of JLabel text.

package org.kodejava.example.swing;

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

public class HTMLLabel extends JFrame {
    public HTMLLabel() {
        setTitle("JLabel with HTML");
        initComponents();
    }

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(400, 200);
        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.CENTER));

        // Create a JLabel object that display a string formatted using HTML.
        // 14 font size with red and italic.
        String text = "<html><font size=\"14\" color=\"ff0000\"><i>Hello World</i></font></html>";
        JLabel label = new JLabel(text);
        container.add(label);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new HTMLLabel().setVisible(true));
    }
}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply