How do I add a title to a border?

This example shows you how to create a border that have a title in it. There is a special border class the TitledBorder that does this. We can define the justification of the title, left, centered or right justify. To do this we call the setTitleJustification() method. We can also set other attributes such as font or the title position.

package org.kodejava.example.swing;

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

public class TitledBorderExample extends JFrame {
    public TitledBorderExample() {

    private void initializeUI() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        TitledBorder border = new TitledBorder(" Form Data ");

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1, 2));

        JLabel usernameLabel = new JLabel("Username: ");
        JTextField usernameField = new JTextField();


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TitledBorderExample().setVisible(true);

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.