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
package com.example.client.utils;
 
import com.example.client.dto.JComboBoxItem;
import org.apache.commons.lang3.math.NumberUtils;
 
import javax.swing.*;
import java.awt.*;
import java.util.Map;
 
// 自定义编辑器
public class CellComboBoxEditor extends DefaultCellEditor {
    private final Map<Long, JComboBoxItem> itemMap;
 
    public CellComboBoxEditor(JComboBox<JComboBoxItem> comboBox, Map<Long, JComboBoxItem> itemMap) {
        super(comboBox);
        this.itemMap = itemMap;
    }
 
    @Override
    public Object getCellEditorValue() {
        JComboBoxItem selectedItem = (JComboBoxItem) super.getCellEditorValue();
        if (selectedItem != null) {
            return selectedItem.getId(); // 返回 id
        }
        return null;
    }
 
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        if (NumberUtils.isDigits(value.toString())) {
            String valueStr = value.toString();
            long id = Long.parseLong(valueStr);
            JComboBoxItem item = itemMap.get(id);
            if (item != null) {
                ((JComboBox<JComboBoxItem>) getComponent()).setSelectedItem(item); // 设置选中项
            }
        }
        return super.getTableCellEditorComponent(table, value, isSelected, row, column);
    }
}