在 Java Swing 開發中,JButton 是最基礎也最常用的元件之一。掌握其核心屬性配置,能讓介面更美觀、互動體驗更佳。本文整理 9 大實用設定,附完整程式碼範例,助你快速上手。
使用 setPreferredSize() 指定寬高(單位:像素),配合佈局管理器生效:
button.setPreferredSize(new Dimension(100, 40));
呼叫 setContentAreaFilled(false) 可讓按鈕背景透明,僅顯示文字或圖標,適合自訂繪圖:
button.setContentAreaFilled(false);
setBorderPainted(false) 關閉預設邊框繪製,常搭配透明背景使用:
button.setBorderPainted(false);
兩種方式皆可,建議使用資源路徑載入:
// 方式一:建構子傳入 ImageIcon
ImageIcon icon = new ImageIcon(getClass().getResource("/icons/ok.png"));
JButton button = new JButton(icon);
// 方式二:後設定
button.setIcon(new ImageIcon(getClass().getResource("/icons/cancel.png")));
將 margin 設為零,按鈕大小將完全由圖標決定:
button.setMargin(new Insets(0, 0, 0, 0));
模擬 3D 按下效果,適用於工具列按鈕:
button.setBorder(BorderFactory.createRaisedBevelBorder());
按下時的視覺回饋,常用於切換狀態按鈕:
button.setBorder(BorderFactory.createLoweredBevelBorder());
設定字型、大小、粗體及顏色:
button.setFont(new Font("微軟正黑體", Font.BOLD, 16));
button.setForeground(Color.WHITE);
button.setBackground(new Color(0, 120, 215));
在程式啟動早期呼叫,影響所有 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 使用者介面。