Java?Swing實現(xiàn)自定義按鈕組件的完整代碼
一、這個類解決什么問題?
Swing 原生按鈕 JButton 本身功能完整,但實際項目中經(jīng)常需要:
- 統(tǒng)一按鈕的樣式(背景色、字體、邊框)
- 鼠標懸停時改變光標和背景色
- 按鈕帶圖標
- 快速創(chuàng)建特定場景的按鈕(搜索按鈕、重置按鈕、操作列按鈕等)
如果每次都用原生寫法,代碼會非常冗余。ButtonUtils 的作用就是:封裝常用按鈕的創(chuàng)建邏輯,一行代碼搞定。
二、類源碼
import cn.hutool.core.util.StrUtil;
import com.hyjk.met.base.module.constant.MetConstants;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.function.Consumer;
/**
* 按鈕工具類
* 封裝 Swing 按鈕的常用創(chuàng)建方法
* * 使用示例:
* 1. 創(chuàng)建默認樣式按鈕:
* JButton btn = ButtonUtils.createDefaultBtn("查詢", () -> doSearch());
* 2. 創(chuàng)建帶圖標的按鈕:
* JButton btn = ButtonUtils.createActionBtn("導出", "icons/export.png", () -> export());
* 3. 創(chuàng)建表格操作列按鈕:
* JButton btn = ButtonUtils.createOperateColBtn("編輯", editIcon, "#409EFF", "#FFFFFF", () -> edit(rowData));
*/
public class ButtonUtils {
/** 默認的按鈕顏色 */
public static final String COLOR_BTN = "#34AE7F";
/** 白色字體 */
public static final String COLOR_WHITE = "#FFFFFF";
/** 默認的字體名稱 */
public static final String FONT_NAME = "Microsoft YaHei";
// ==================== 標簽按鈕(Label模擬) ====================
/**
* 創(chuàng)建標簽按鈕(用 JLabel 模擬按鈕)
* @param text 按鈕文字
* @param icon 圖標路徑
* @param btnAction 點擊事件
* @return 標簽按鈕
*/
public static JLabel createLabelBtn(String text, String icon, Runnable btnAction) {
// 獲取圖片
// ImageIcon imageIcon = ;
JLabel btn = new JLabel(imageIcon);
btn.setText(text);
btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (null != btnAction) {
btnAction.run();
}
}
});
return btn;
}
// ==================== 表單按鈕 ====================
/**
* 創(chuàng)建表單按鈕(固定高度50,綠色背景白色文字)
* @param btnText 按鈕文字
* @param btnIcon 圖標路徑
* @param btnAction 點擊事件
* @return 按鈕
*/
public static JButton createFormBtn(String btnText, String btnIcon, Runnable btnAction) {
JButton button = createActionBtn(btnText, btnIcon, btnAction);
button.setPreferredSize(new Dimension(button.getPreferredSize().width, 50));
button.setBackground(Color.decode(COLOR_BTN));
button.setForeground(Color.WHITE);
button.setBorderPainted(false);
button.setIconTextGap(15);
return button;
}
// ==================== 文本按鈕 ====================
/**
* 創(chuàng)建文本按鈕(用 JLabel 模擬,默認主題色)
* @param text 文字
* @param mouseClicked 點擊事件
* @return 標簽按鈕
*/
public static JLabel createTextBtn(String text, Runnable mouseClicked) {
return createTextBtn(text, Color.decode(COLOR_BTN), mouseClicked);
}
/**
* 創(chuàng)建文本按鈕(可指定字體顏色)
* @param text 文字
* @param fontColor 字體顏色
* @param mouseClicked 點擊事件
* @return 標簽按鈕
*/
public static JLabel createTextBtn(String text, Color fontColor, Runnable mouseClicked) {
JLabel textBtn = new JLabel(text);
textBtn.setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 0));
textBtn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
textBtn.setForeground(fontColor);
textBtn.setFont(new Font(FONT_NAME, Font.BOLD, 16));
textBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (null != mouseClicked) {
mouseClicked.run();
}
}
});
return textBtn;
}
// ==================== 通用按鈕創(chuàng)建 ====================
/**
* 創(chuàng)建按鈕(最靈活版本)
* @param text 按鈕文字
* @param bgColorHex 背景色(十六進制)
* @param fontColorHex 字體顏色
* @param mouseClick 點擊事件
* @param mouseEntered 鼠標進入事件(可為null)
* @param mouseExited 鼠標離開事件(可為null)
* @return 按鈕
*/
public static JButton createActionBtn(String text, String bgColorHex, String fontColorHex,
Runnable mouseClick, Consumer<JComponent> mouseEntered,
Consumer<JComponent> mouseExited) {
JButton button = new JButton(text);
button.setMargin(new Insets(5, 10, 5, 10));
button.setFont(new Font(FONT_NAME, Font.PLAIN, 16));
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
button.setBackground(StrUtil.isNotBlank(bgColorHex) ? Color.decode(bgColorHex) : Color.decode("#F2F3F5"));
button.setForeground(StrUtil.isNotBlank(fontColorHex) ? Color.decode(fontColorHex) : Color.decode("#666666"));
button.setBorderPainted(false);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
if (null != mouseEntered) {
mouseEntered.accept(button);
}
}
@Override
public void mouseExited(MouseEvent e) {
if (null != mouseExited) {
mouseExited.accept(button);
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (null != mouseClick) {
mouseClick.run();
}
}
});
return button;
}
/**
* 創(chuàng)建按鈕(帶圖標)
* @param text 按鈕文字
* @param iconPath 圖標路徑
* @param bgColorHex 背景色
* @param fontColorHex 字體顏色
* @param mouseClick 點擊事件
* @param mouseEntered 鼠標進入事件
* @param mouseExited 鼠標離開事件
* @return 按鈕
*/
public static JButton createActionBtn(String text, String iconPath, String bgColorHex, String fontColorHex,
Runnable mouseClick, Consumer<JComponent> mouseEntered,
Consumer<JComponent> mouseExited) {
JButton button = createActionBtn(text, bgColorHex, fontColorHex, mouseClick, mouseEntered, mouseExited);
if (StrUtil.isNotBlank(iconPath)) {
// 需自行實現(xiàn),獲取圖片
// button.setIcon();
}
return button;
}
/**
* 創(chuàng)建按鈕(帶圖標,無背景色/字體色設置)
* @param text 按鈕文字
* @param iconPath 圖標路徑
* @param mouseClick 點擊事件
* @param mouseEntered 鼠標進入事件
* @param mouseExited 鼠標離開事件
* @return 按鈕
*/
public static JButton createActionBtn(String text, String iconPath, Runnable mouseClick,
Consumer<JComponent> mouseEntered, Consumer<JComponent> mouseExited) {
return createActionBtn(text, iconPath, "", "", mouseClick, mouseEntered, mouseExited);
}
/**
* 創(chuàng)建按鈕(無圖標,帶懸停回調)
* @param text 按鈕文字
* @param mouseClick 點擊事件
* @param mouseEntered 鼠標進入事件
* @param mouseExited 鼠標離開事件
* @return 按鈕
*/
public static JButton createActionBtn(String text, Runnable mouseClick,
Consumer<JComponent> mouseEntered, Consumer<JComponent> mouseExited) {
return createActionBtn(text, "", "", mouseClick, mouseEntered, mouseExited);
}
/**
* 創(chuàng)建按鈕(帶圖標和背景色,無懸停回調)
* @param text 按鈕文字
* @param iconPath 圖標路徑
* @param bgColorHex 背景色
* @param fontColorHex 字體顏色
* @param mouseClick 點擊事件
* @return 按鈕
*/
public static JButton createActionBtn(String text, String iconPath, String bgColorHex,
String fontColorHex, Runnable mouseClick) {
return createActionBtn(text, iconPath, bgColorHex, fontColorHex, mouseClick, null, null);
}
/**
* 創(chuàng)建按鈕(帶背景色,無圖標)
* @param text 按鈕文字
* @param bgColorHex 背景色
* @param fontColorHex 字體顏色
* @param mouseClick 點擊事件
* @return 按鈕
*/
public static JButton createActionBtn(String text, String bgColorHex, String fontColorHex, Runnable mouseClick) {
return createActionBtn(text, "", bgColorHex, fontColorHex, mouseClick);
}
/**
* 創(chuàng)建按鈕(帶圖標,默認背景色)
* @param text 按鈕文字
* @param iconPath 圖標路徑
* @param mouseClick 點擊事件
* @return 按鈕
*/
public static JButton createActionBtn(String text, String iconPath, Runnable mouseClick) {
return createActionBtn(text, iconPath, "", "", mouseClick);
}
/**
* 創(chuàng)建按鈕(純文字,默認背景色)
* @param text 按鈕文字
* @param mouseClick 點擊事件
* @return 按鈕
*/
public static JButton createActionBtn(String text, Runnable mouseClick) {
return createActionBtn(text, "", mouseClick);
}
// ==================== 操作列按鈕 ====================
/**
* 創(chuàng)建表格操作列按鈕(尺寸緊湊)
* @param text 按鈕文字
* @param imageIcon 圖標
* @param bgColorHex 背景色
* @param fontColorHex 字體顏色
* @param mouseClick 點擊事件
* @return 按鈕
*/
public static JButton createOperateColBtn(String text, ImageIcon imageIcon, String bgColorHex,
String fontColorHex, Runnable mouseClick) {
JButton button = createActionBtn(text, imageIcon, bgColorHex, fontColorHex, mouseClick);
button.setMargin(new Insets(2, 8, 2, 8));
button.setFont(new Font(FONT_NAME, Font.PLAIN, 15));
Dimension dimension = button.getPreferredSize();
button.setPreferredSize(dimension);
button.setMinimumSize(dimension);
button.setMaximumSize(dimension);
return button;
}
// ==================== 快捷按鈕 ====================
/**
* 創(chuàng)建默認樣式按鈕(主題色背景白色文字)
* @param text 按鈕文字
* @param mouseClick 點擊事件
* @return 按鈕
*/
public static JButton createDefaultBtn(String text, Runnable mouseClick) {
return createActionBtn(text, COLOR_BTN, COLOR_WHITE, mouseClick);
}
/**
* 創(chuàng)建帶圖標的默認樣式按鈕
* @param text 按鈕文字
* @param iconPath 圖標路徑
* @param mouseClick 點擊事件
* @return 按鈕
*/
public static JButton createDefaultBtn(String text, String iconPath, Runnable mouseClick) {
return createActionBtn(text, iconPath, COLOR_BTN, COLOR_WHITE, mouseClick);
}
/**
* 添加查詢面板搜索按鈕
* @param parent 父面板
* @param mouseClick 點擊事件
*/
public static void createSearchBtn(JComponent parent, Runnable mouseClick) {
createSearchBtn(parent, "查詢", mouseClick);
}
/**
* 添加查詢面板搜索按鈕(可自定義文字)
* @param parent 父面板
* @param text 按鈕文字
* @param mouseClick 點擊事件
*/
public static void createSearchBtn(JComponent parent, String text, Runnable mouseClick) {
// 搜索圖片存儲位置,如 icons/table/search-white.png
String iconPath = "";
JButton button = createActionBtn(text, iconPath, "#34AE7F", "#FFFFFF", mouseClick);
parent.add(button);
}
/**
* 添加查詢面板重置按鈕
* @param parent 父面板
* @param mouseClick 點擊事件
*/
public static void createResetBtn(JComponent parent, Runnable mouseClick) {
createResetBtn(parent, "重置", mouseClick);
}
/**
* 添加查詢面板重置按鈕(可自定義文字)
* @param parent 父面板
* @param text 按鈕文字
* @param mouseClick 點擊事件
*/
public static void createResetBtn(JComponent parent, String text, Runnable mouseClick) {
// 重置圖片存儲位置,如 icons/table/reset-gray.png
String iconPath = "";
JButton button = createActionBtn(text, iconPath, mouseClick);
parent.add(button);
}
}
三、核心方法說明
標簽按鈕(Label模擬):createLabelBtn:用 JLabel 模擬按鈕,適合圖標+文字的簡單點擊場景
表單按鈕:createFormBtn:固定高度50,綠色背景白色文字,適合表單提交按鈕
文本按鈕:createTextBtn:用 JLabel 模擬超鏈接樣式,適合“忘記密碼”等場景
通用按鈕:createActionBtn:最靈活的按鈕創(chuàng)建方法,提供多個重載版本
操作列按鈕:createOperateColBtn:表格行內(nèi)操作按鈕,尺寸緊湊
快捷按鈕: createDefaultBtn:默認樣式(主題色背景白色文字) createSearchBtn / createResetBtn:快捷創(chuàng)建查詢/重置按鈕并添加到父面板
四、使用示例
4.1 創(chuàng)建默認樣式按鈕
JButton searchBtn = ButtonUtils.createDefaultBtn("查詢", () -> {
System.out.println("執(zhí)行查詢");
});
panel.add(searchBtn);
4.2 創(chuàng)建帶圖標按鈕
// 圖片存儲位置,如 icons/export.png
String iconPath = "";
JButton exportBtn = ButtonUtils.createActionBtn("導出", iconPath, () -> {
System.out.println("執(zhí)行導出");
});
panel.add(exportBtn);
4.3 創(chuàng)建自定義顏色按鈕
JButton dangerBtn = ButtonUtils.createActionBtn("刪除", "#F56C6C", "#FFFFFF", () -> {
int result = JOptionPane.showConfirmDialog(null, "確認刪除?", "提示", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
System.out.println("執(zhí)行刪除");
}
});
panel.add(dangerBtn);
4.4 創(chuàng)建文本按鈕(超鏈接樣式)
JLabel linkLabel = ButtonUtils.createTextBtn("忘記密碼?", () -> {
System.out.println("跳轉到找回密碼");
});
panel.add(linkLabel);
4.5 查詢面板中使用
JPanel queryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
queryPanel.add(new JLabel("用戶名:"));
queryPanel.add(new JTextField(10));
ButtonUtils.createSearchBtn(queryPanel, this::doSearch);
ButtonUtils.createResetBtn(queryPanel, this::doReset);
4.6 表格操作列中使用
// 獲取圖片ImageIcon
//ImageIcon editIcon = xxxx;
JButton editBtn = ButtonUtils.createOperateColBtn("編輯", editIcon, "#409EFF", "#FFFFFF", () -> {
System.out.println("編輯行數(shù)據(jù)");
});
五、方法重載說明
createActionBtn 提供了多個重載版本:
| 參數(shù)情況 | 使用方法 |
|---|---|
| 只要文字+點擊事件 | createActionBtn(text, runnable) |
| 文字+圖標+點擊事件 | createActionBtn(text, iconPath, runnable) |
| 文字+背景色+字體色+點擊事件 | createActionBtn(text, bgColor, fontColor, runnable) |
| 文字+圖標+背景色+字體色+點擊事件 | createActionBtn(text, iconPath, bgColor, fontColor, runnable) |
| 需要自定義懸停效果 | createActionBtn(text, runnable, mouseEntered, mouseExited) |
六、注意事項
- 代碼中涉及圖標的地方已注釋或標注,需要自行實現(xiàn)圖標加載
- 使用了 COLOR_BTN、COLOR_WHITE、FONT_NAME,讀者可在自己的常量類中定義
七、小結
ButtonUtils 封裝了 Swing 按鈕的常見創(chuàng)建場景,核心設計思路:
- 統(tǒng)一樣式:背景色、字體色、邊框、光標
- 簡化調用:一行代碼完成按鈕創(chuàng)建
- 靈活擴展:支持多種參數(shù)組合和自定義懸停效果
以上就是Java Swing實現(xiàn)自定義按鈕組件的完整代碼的詳細內(nèi)容,更多關于Java Swing自定義按鈕組件的資料請關注腳本之家其它相關文章!
相關文章
sharding-jdbc 兼容 MybatisPlus動態(tài)數(shù)據(jù)源的配置方法
這篇文章主要介紹了sharding-jdbc 兼容 MybatisPlus動態(tài)數(shù)據(jù)源的配置方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-07-07
如何使用IntelliJ?IDEA寫一個簡單的JSP網(wǎng)頁
目前市場上流傳很多jsp項目,雖然是很老的項目,但是對于畢業(yè)設計項目來說還是很好的學習項目,下面這篇文章主要介紹了如何使用IntelliJ?IDEA寫一個簡單的JSP網(wǎng)頁,需要的朋友可以參考下2025-07-07
Mybatis反射核心類Reflector的實現(xiàn)
本文主要介紹了Mybatis反射核心類Reflector的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11
基于SpringBoot和Vue實現(xiàn)分片上傳系統(tǒng)
最近想做一個關于文件上傳的個人小網(wǎng)盤,一開始嘗試使用了OSS的方案,但是該方案對于大文件來說并不友好,所以開始嘗試分片上傳方案的探索,接下來小編給大家詳細的介紹一下如何基于SpringBoot和Vue實現(xiàn)分片上傳系統(tǒng),需要的朋友可以參考下2023-12-12
從0到1學SpringCloud之SpringCloud?gateway網(wǎng)關路由配置示例詳解
Spring?Cloud?Gateway的目標提供統(tǒng)一的路由方式且基于Filter?鏈的方式提供了網(wǎng)關基本的功能,?例如:安全、監(jiān)控、指標和限流?,這篇文章主要介紹了從0到1學SpringCloud之SpringCloud?gateway網(wǎng)關路由配置示例詳解,需要的朋友可以參考下2023-04-04
Spring Security @PreAuthorize注解分析
本教程介紹了如何使用 Spring 方法級安全和 @PreAuthorize 注解來保護 RestController 方法,通過這些步驟,您可以確保只有具有適當角色或權限的用戶才能訪問特定的 REST API,感興趣的朋友跟隨小編一起看看吧2024-11-11

