package com.example.client.utils;
|
|
import com.example.client.dto.ColumnDto;
|
|
import javax.swing.*;
|
import javax.swing.plaf.basic.BasicComboBoxEditor;
|
import javax.swing.table.DefaultTableCellRenderer;
|
import javax.swing.table.TableColumnModel;
|
import java.awt.*;
|
import java.util.HashSet;
|
import java.util.List;
|
import java.util.Set;
|
|
public class ColorDescriptionComboBox extends JComboBox<ColorDescription> {
|
private String defaultText; // 默认显示文本
|
|
public ColorDescriptionComboBox(List<ColorDescription> colorDescriptions) {
|
super(colorDescriptions.toArray(new ColorDescription[0]));
|
this.defaultText = "状态"; // 设置默认文本
|
setEditable(true);
|
|
// 自定义渲染器
|
setRenderer(new DefaultListCellRenderer() {
|
@Override
|
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
|
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
|
if (value instanceof ColorDescription) {
|
ColorDescription cd = (ColorDescription) value;
|
setText(cd.getDescription()); // 显示描述
|
setIcon(new ColorIcon(cd.getHexColor())); // 设置圆形图标
|
}
|
return this;
|
}
|
});
|
|
// 自定义编辑器
|
setEditor(new BasicComboBoxEditor() {
|
private JTextField textField;
|
|
@Override
|
public Component getEditorComponent() {
|
if (textField == null) {
|
textField = new JTextField(defaultText); // 设置默认文本
|
textField.setEditable(false); // 设置为不可编辑
|
}
|
return textField;
|
}
|
|
@Override
|
public void setItem(Object anObject) {
|
if (anObject instanceof ColorDescription) {
|
ColorDescription cd = (ColorDescription) anObject;
|
textField.setText(cd.getDescription()); // 设置编辑器文本为描述
|
} else {
|
textField.setText(defaultText); // 设置默认文本
|
}
|
}
|
});
|
}
|
}
|
|
|
// 自定义圆形图标类
|
class ColorIcon implements Icon {
|
private Color color;
|
|
public ColorIcon(String hexColor) {
|
this.color = ColorUtils.hexToColor(hexColor);
|
}
|
|
@Override
|
public void paintIcon(Component c, Graphics g, int x, int y) {
|
int width = getIconWidth();
|
int height = getIconHeight();
|
int diameter = Math.min(width, height);
|
int xCenter = (width - diameter) / 2;
|
int yCenter = (height - diameter) / 2;
|
|
g.setColor(color);
|
g.fillOval(x + xCenter, y + yCenter, diameter, diameter);
|
}
|
|
@Override
|
public int getIconWidth() {
|
return 20; // 圆形的宽度
|
}
|
|
@Override
|
public int getIconHeight() {
|
return 20; // 圆形的高度
|
}
|
}
|
// 十六进制颜色转换为 Color 对象
|
class ColorUtils {
|
public static Color hexToColor(String hex) {
|
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;
|
}
|
}
|
}
|