Java如何为边框添加标题?

本示例说明如何创建带有标题的边框。有一个特殊的边界类TitledBorder可以做到这一点。我们可以定义标题的对齐方式,左对齐,居中对齐或右对齐。为此,我们调用该setTitleJustification()方法。我们还可以设置其他属性,例如字体或标题位置。

package org.nhooo.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(WindowConstants.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);
            }
        });
    }
}