首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Swing 邊框藝術:八大內建邊框與組合邊框實戰

     編輯:Java 相關知識

核心 API

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()...
}

進階技巧

1. 自定義邊框


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; }
}

2. 邊框組合策略


// 外層刻蝕 + 內層紅線 + 內邊距 10px
Border border = new CompoundBorder(
    new EtchedBorder(),
    new CompoundBorder(
        new LineBorder(Color.RED, 2),
        new EmptyBorder(10, 10, 10, 10)
    )
);
component.setBorder(border);

3. 標題邊框客製化


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 控制內邊距,即能輕鬆打造專業視覺層次。自定義邊框僅需實作三個方法,可實現漸變、圖片、動畫等無限創意效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved