jinlin
2025-03-18 d30e385951ce03335a5023f0775fd144da3c0b88
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.example.client.utils;
 
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
 
public class CircleRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
 
        // 将十六进制字符串转换为 Color 对象
        if (value instanceof String) {
            String hexColor = (String) value;
            Color color = hexToColor(hexColor);
            setForeground(color); // 设置前景色为圆形的颜色
        }
 
        // 设置背景色(可选)
        setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
 
        // 设置文本为空,因为我们只显示圆形图案
        setText("");
 
        return this;
    }
 
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
 
        // 绘制圆形图案
        int width = getWidth();
        int height = getHeight();
        int diameter = Math.min(width, height); // 圆的直径
        int x = (width - diameter) / 2;
        int y = (height - diameter) / 2;
 
        g.setColor(getForeground());
        g.fillOval(x, y, diameter, diameter); // 绘制填充的圆形
    }
 
    // 将十六进制字符串转换为 Color 对象
    private Color hexToColor(String hex) {
        if (hex == null || hex.isEmpty()) {
            return Color.WHITE; // 默认颜色
        }
        try {
            // 去掉可能存在的 "#" 前缀
            hex = hex.trim().replace("#", "");
            int rgb = Integer.parseInt(hex, 16);
            return new Color((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);
        } catch (NumberFormatException e) {
            return Color.WHITE; // 如果转换失败,返回默认颜色
        }
    }
}