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);
}
});
}
}
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短