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; // 所有部分都是纯数字
|
}
|
}
|