张世豪
4 天以前 32c98d4855b6178554c787103dc956d161e152b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package ui;
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
 
/**
 * 一些通用 UI 工具函数(例如创建图片按钮),统一样式与交互行为
 */
public final class UIUtils {
    private UIUtils() {}
 
    public static JButton createImageButton(String imagePath, String toolTip) {
        JButton button = new JButton();
        button.setBackground(Color.WHITE);
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        button.setPreferredSize(UIConfig.IMAGE_BUTTON_PREFERRED);
        button.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));
        button.setToolTipText(toolTip);
 
        try {
            ImageIcon icon = new ImageIcon(imagePath);
            Image img = icon.getImage();
            Image scaled = img.getScaledInstance(UIConfig.IMAGE_ICON_SIZE, UIConfig.IMAGE_ICON_SIZE, Image.SCALE_SMOOTH);
            button.setIcon(new ImageIcon(scaled));
        } catch (Exception ex) {
            button.setText(toolTip);
            System.err.println("无法加载图片: " + imagePath + " - " + ex.getMessage());
        }
 
        button.setMargin(new Insets(0, 0, 0, 0));
 
        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) { button.setBackground(new Color(245, 245, 245)); }
            public void mouseExited(MouseEvent e) { button.setBackground(Color.WHITE); }
        });
 
        return button;
    }
}