package publicway;
|
|
import javax.swing.*;
|
import java.awt.*;
|
import java.awt.event.ActionListener;
|
import java.awt.event.MouseAdapter;
|
import java.awt.event.MouseEvent;
|
|
/**
|
* 查看按钮工具类
|
* 提供统一的查看按钮创建方法,默认显示查看图标,点击按钮执行对应的操作
|
*/
|
public final class Lookbutton {
|
|
// 默认图标大小
|
private static final int DEFAULT_ICON_SIZE =25;
|
|
private Lookbutton() {
|
// 工具类不需要实例化
|
}
|
|
/**
|
* 创建查看按钮
|
* 默认显示 image/look.png 图标,点击按钮执行传入的操作
|
*
|
* @param listener 按钮点击事件监听器,当按钮被点击时执行
|
* @param hoverColor 鼠标悬停时的背景颜色(如果为null,使用默认颜色)
|
* @return 配置好的查看按钮
|
*/
|
public static JButton createViewButton(ActionListener listener, Color hoverColor) {
|
JButton viewButton = new JButton();
|
|
// 加载图标
|
ImageIcon lookIcon = loadIcon("image/look.png", DEFAULT_ICON_SIZE, DEFAULT_ICON_SIZE);
|
|
// 设置按钮图标
|
if (lookIcon != null) {
|
viewButton.setIcon(lookIcon);
|
} else {
|
viewButton.setText("查看");
|
}
|
|
// 设置按钮样式
|
viewButton.setFont(new Font("微软雅黑", Font.PLAIN, 11));
|
viewButton.setForeground(new Color(46, 139, 87)); // PRIMARY_COLOR
|
viewButton.setBorder(BorderFactory.createEmptyBorder());
|
viewButton.setContentAreaFilled(false);
|
viewButton.setFocusPainted(false);
|
viewButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
|
|
// 设置提示文本为"点击查看"
|
viewButton.setToolTipText("点击查看");
|
|
// 设置悬停效果
|
final Color finalHoverColor = hoverColor != null ? hoverColor : new Color(230, 250, 240);
|
viewButton.addMouseListener(new MouseAdapter() {
|
public void mouseEntered(MouseEvent e) {
|
viewButton.setOpaque(true);
|
viewButton.setBackground(finalHoverColor);
|
}
|
|
public void mouseExited(MouseEvent e) {
|
viewButton.setOpaque(false);
|
}
|
});
|
|
// 添加点击事件
|
if (listener != null) {
|
viewButton.addActionListener(listener);
|
}
|
|
return viewButton;
|
}
|
|
/**
|
* 创建查看按钮(使用默认悬停颜色)
|
*
|
* @param listener 按钮点击事件监听器,当按钮被点击时执行
|
* @return 配置好的查看按钮
|
*/
|
public static JButton createViewButton(ActionListener listener) {
|
return createViewButton(listener, null);
|
}
|
|
/**
|
* 加载图标并调整大小
|
*
|
* @param path 图标路径
|
* @param width 目标宽度
|
* @param height 目标高度
|
* @return 调整大小后的图标,如果加载失败返回null
|
*/
|
private static ImageIcon loadIcon(String path, int width, int height) {
|
try {
|
ImageIcon rawIcon = new ImageIcon(path);
|
if (rawIcon.getIconWidth() <= 0 || rawIcon.getIconHeight() <= 0) {
|
return null;
|
}
|
Image scaled = rawIcon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);
|
return new ImageIcon(scaled);
|
} catch (Exception ex) {
|
System.err.println("无法加载图标: " + path + " - " + ex.getMessage());
|
return null;
|
}
|
}
|
}
|