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

Java Swing JButton 核心配置全攻略:從尺寸、透明度到圖標與邊框美化

     編輯:Java 綜合教學

JButton 常用屬性設定完整指南

在 Java Swing 開發中,JButton 是最基礎也最常用的元件之一。掌握其核心屬性配置,能讓介面更美觀、互動體驗更佳。本文整理 9 大實用設定,附完整程式碼範例,助你快速上手。

1. 設定按鈕固定尺寸

使用 setPreferredSize() 指定寬高(單位:像素),配合佈局管理器生效:

button.setPreferredSize(new Dimension(100, 40));

2. 移除內容區域填充(透明背景)

呼叫 setContentAreaFilled(false) 可讓按鈕背景透明,僅顯示文字或圖標,適合自訂繪圖:

button.setContentAreaFilled(false);

3. 隱藏邊框線條

setBorderPainted(false) 關閉預設邊框繪製,常搭配透明背景使用:

button.setBorderPainted(false);

4. 添加圖標

兩種方式皆可,建議使用資源路徑載入:

// 方式一:建構子傳入 ImageIcon
ImageIcon icon = new ImageIcon(getClass().getResource("/icons/ok.png"));
JButton button = new JButton(icon);

// 方式二:後設定
button.setIcon(new ImageIcon(getClass().getResource("/icons/cancel.png")));

5. 讓按鈕緊貼圖標(移除內邊距)

將 margin 設為零,按鈕大小將完全由圖標決定:

button.setMargin(new Insets(0, 0, 0, 0));

6. 立體凸起邊框

模擬 3D 按下效果,適用於工具列按鈕:

button.setBorder(BorderFactory.createRaisedBevelBorder());

7. 立體凹陷邊框

按下時的視覺回饋,常用於切換狀態按鈕:

button.setBorder(BorderFactory.createLoweredBevelBorder());

8. 自訂字體與前景/背景色

設定字型、大小、粗體及顏色:

button.setFont(new Font("微軟正黑體", Font.BOLD, 16));
button.setForeground(Color.WHITE);
button.setBackground(new Color(0, 120, 215));

9. 切換全域 Look & Feel

在程式啟動早期呼叫,影響所有 Swing 元件外觀:

try {
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
    e.printStackTrace();
}

實戰小技巧

  • 組合使用 setContentAreaFilled(false) + setBorderPainted(false) + 圖標,打造現代化扁平化按鈕。
  • 利用 setRolloverIcon()、setPressedIcon() 實現滑鼠懸停/按下狀態圖示切換。
  • 若需圓角按鈕,可繼承 JButton 覆寫 paintComponent() 繪製圓角矩形。

掌握這些核心設定,你就能靈活打造出專業級的 Swing 使用者介面。

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