0

我正在尝试使用在 Colour.java 中声明的枚举填充 JComboBox。我可以使用 Colour.values() 访问枚举的描述,但是否可以访问枚举声明本身?我想要用蓝色和红色填充的 JComboBox。我查看了http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html无济于事。

package example;
import javax.swing.*;

public class ColourView extends View {

private JLabel colourLabel;
private JComboBox comboBox;
private DefaultComboBoxModel model;

public ColourView() {
    colourLabel = new JLabel();
    colourLabel.setText("Colours");
    colourLabel.setBounds(20, 30, 70, 20);
    mainContentLayeredPane.add(colourLabel, JLayeredPane.DEFAULT_LAYER);

    comboBox = new JComboBox(Colour.values());     

    comboBox.setSize(100, 20);
    mainContentLayeredPane.add(comboBox, JLayeredPane.DEFAULT_LAYER);
}

public void setComboBox(String[] list) {
    model = new DefaultComboBoxModel(list);
    comboBox.setModel(model);
}
}

package example;

public enum Colour {
BLUE("Blue Paint", 12),
RED("Red Paint", 4);
private String description;
private int value; 

Colour(String description, int value){
    this.description = description; 
    this.value = value; 
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public int getValue() {
    return value;
}

@Override
public String toString() {
    return description;
}
}
4

1 回答 1

2

如果您希望在颜色名称旁边显示相同颜色的小样本,则需要自定义渲染器。如果您从 a 开始DefaultListCellRenderer,您可以添加一个Icon用相同颜色绘制的,或者像这里显示的那样更改背景。

于 2013-03-25T12:30:46.023 回答