jinlin
4 天以前 66f0597bf6a1e79540c6bc51dedf561c22f3bdb5
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.example.client.utils;
 
import com.example.client.dto.JComboBoxItem;
import org.apache.commons.lang3.math.NumberUtils;
 
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.util.Map;
 
public class CellComboBoxRenderer implements TableCellRenderer {
    private final Map<Long, JComboBoxItem> itemMap;
 
    public CellComboBoxRenderer(Map<Long, JComboBoxItem> itemMap) {
        this.itemMap = itemMap;
    }
 
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        JLabel label = new JLabel();
        String valueStr = value.toString();
        if (NumberUtils.isDigits(valueStr)) {
            // 单个数字的情况
            long id = Long.parseLong(valueStr);
            JComboBoxItem item = itemMap.get(id);
            label.setText(item != null ? item.getName() : "Unknown");
        } else if(this.isCommaSeparatedDigits(valueStr)){
            StringBuilder text = new StringBuilder();
            String[] stringArray = valueStr.split(",");
 
            for (String str : stringArray) {
                try {
                    long id = Long.parseLong(str.trim());
                    JComboBoxItem item = itemMap.get(id);
                    if (item != null) {
                        if (text.length() > 0) {
                            text.append(", ");
                        }
                        text.append(item.getName());
                    }
                } catch (NumberFormatException e) {
                    // 如果某个值不是有效的数字,跳过它
                    continue;
                }
            }
            label.setText(text.toString());
        }
 
        if (isSelected) {
            label.setBackground(table.getSelectionBackground());
            label.setForeground(table.getSelectionForeground());
        } else {
            label.setBackground(table.getBackground());
            label.setForeground(table.getForeground());
        }
 
        return label;
    }
 
    private boolean isCommaSeparatedDigits(String input) {
        if (input == null || !input.contains(",")) {
            return false; // 不包含逗号,不是逗号分隔的字符串
        }
 
        String[] parts = input.split(",");
        for (String part : parts) {
            if (!NumberUtils.isDigits(part.trim())) {
                return false; // 如果某个部分不是纯数字,则返回 false
            }
        }
 
        return true; // 所有部分都是纯数字
    }
}