JComponent.setBorder(Border) 賦予所有 Swing 元件邊框裝飾能力。javax.swing.border 套件提供豐富實現,支援**組合嵌套**。
| 邊框類別 | 視覺效果 | 典型用途 |
|---|---|---|
TitledBorder | 帶標題文字的線框 | 分組面板標題 |
EtchedBorder | 凹/凸 3D 刻蝕線 | 面板分隔、視覺層次 |
LineBorder | 純色實線/虛線 | 簡單框線、高亮聚焦 |
MatteBorder | 圖片/顏色平鋪填充 | 裝飾性邊框、品牌標識 |
BevelBorder | 立體斜角 (RAISED/LOWERED) | 按鈕、欄位立體感 |
SoftBevelBorder | 柔和斜角 | 現代扁平化風格 |
CompoundBorder | **外層 + 內層** 雙重邊框 | 複合視覺效果 (如刻蝕+紅線) |
EmptyBorder | 透明間距 (無視覺線) | 元件內邊距、佈局微調 |
public class Borders extends JPanel {
public Borders() {
setLayout(new GridLayout(2, 4));
add(makePanel(new TitledBorder("Title")));
add(makePanel(new EtchedBorder()));
add(makePanel(new LineBorder(Color.BLUE)));
add(makePanel(new MatteBorder(5,5,30,30, Color.GREEN)));
add(makePanel(new BevelBorder(BevelBorder.RAISED)));
add(makePanel(new SoftBevelBorder(BevelBorder.LOWERED)));
add(makePanel(new CompoundBorder(
new EtchedBorder(), new LineBorder(Color.RED))));
add(makePanel(new EmptyBorder(10,10,10,10))); // 額外補充
}
static JPanel makePanel(Border border) {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(border);
// 顯示邊框類別簡短名稱
String name = border.getClass().getSimpleName();
p.add(new JLabel(name, JLabel.CENTER), BorderLayout.CENTER);
return p;
}
// main()...
}
class GradientBorder implements Border {
private final Color c1, c2;
public GradientBorder(Color c1, Color c2) { this.c1=c1; this.c2=c2; }
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(new GradientPaint(x, y, c1, x+w, y+h, c2));
g2.drawRect(x, y, w-1, h-1);
}
public Insets getBorderInsets(Component c) { return new Insets(1,1,1,1); }
public boolean isBorderOpaque() { return true; }
}
// 外層刻蝕 + 內層紅線 + 內邊距 10px
Border border = new CompoundBorder(
new EtchedBorder(),
new CompoundBorder(
new LineBorder(Color.RED, 2),
new EmptyBorder(10, 10, 10, 10)
)
);
component.setBorder(border);
TitledBorder tb = new TitledBorder(
new LineBorder(Color.BLUE, 2), // 底層邊框
"用戶資料", // 標題
TitledBorder.LEFT, // 水平位置
TitledBorder.TOP, // 垂直位置
new Font("微軟正黑體", Font.BOLD, 14), // 字型
Color.DARK_BLUE // 顏色
);
Swing 邊框系統以 **Border 介面 + 組合模式** 實現極高靈活性。掌握八大內建邊框特性與 CompoundBorder 組合技巧,配合 EmptyBorder 控制內邊距,即能輕鬆打造專業視覺層次。自定義邊框僅需實作三個方法,可實現漸變、圖片、動畫等無限創意效果。