TitledBorder in Java Swing

In Java Swing, TitledBorder is a class that allows us to add a border with a title to a component. The title can be positioned at the top, bottom, left or right of the border. This is often used to group related components together and make the user interface more organized and easy to understand.

Following is an example of how to use TitledBorder:

import java.awt.BorderLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

public class TitledBorderDemo extends JPanel {

    public TitledBorderDemo() {
        setLayout(new BorderLayout());
        
        // Create a button with a titled border
        JButton button = new JButton("Click me");
        TitledBorder title = BorderFactory.createTitledBorder("My Button");
        button.setBorder(title);
        
        add(button, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("TitledBorder Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setLayout(new BorderLayout());
        
        TitledBorderDemo panel = new TitledBorderDemo();
        frame.add(panel, BorderLayout.NORTH);
        
        frame.setVisible(true);
    }

}

Output:

TitledBorder in java swing

In this example, a new TitledBorder is created using the static method BorderFactory.createTitledBorder(), passing in the desired title as a string parameter. The created border is then set as the button’s border using the setBorder() method. The button is then added to a JPanel with a BorderLayout, and the JPanel is added to a JFrame. When the JFrame is displayed, the button will have a titled border.

Reference: https://docs.oracle.com/javase/tutorial/uiswing/components/border.html