java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to add a title to a border?

This example show 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, for example on the left, centered or right justify. To do this we call the setTitleJustification() method. We can also set other attribute such as font or the title position.

package com.javacoderanch.example.swing;

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

public class TitledBorderExample extends JFrame {
    public TitledBorderExample() {
        initializeUI();
    }

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

        TitledBorder border = new TitledBorder(" Form Data ");
        border.setTitleJustification(TitledBorder.LEFT);
        border.setTitlePosition(TitledBorder.TOP);

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

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

        setContentPane(panel);
    }

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