如何将comboBox对象转换为Color对象

时间:2014-07-07 20:25:28

标签: java object colors combobox casting

到目前为止,我正在尝试执行以下演员而没有运气 - 编译器comliles很好,但我在运行时有例外。 我正在尝试使用从comboBox中选择的颜色绘制框架contentPane。 这是我的代码,它构造了JComboBox对象:

public  RgbComboBoxFrame() {

    colorComboBox = new JComboBox();
    colorComboBox.addItem("RED");
    colorComboBox.addItem("GREEN");
    colorComboBox.addItem("BLUE");
    colorComboBox.setEditable(true);
    listener = new AddListener();
    paintContentPane();
    createPanel();
    setSize(FRAME_WIDTH,FRAME_HEIGHT);
}

这是我的方法。在这里我试图通过演员解决问题:

private void paintContentPane(){
    Color c = (Color)colorComboBox.getSelectedItem();

    getContentPane().setBackground(c);
}

1 个答案:

答案 0 :(得分:1)

如果你想这样做:

Color c = (Color)colorComboBox.getSelectedItem();

然后,您必须将实际的Color对象添加到组合框中。转换只是对编译器说“我知道我在做什么,所以让它通过”的一种方式。它允许您编写类型在编译时不一定匹配的代码,但您知道它将是运行时。 (简单来说)。你想写这个:

colorComboBox = new JComboBox();
colorComboBox.addItem(Color.red);
colorComboBox.addItem(Color.green);
colorComboBox.addItem(Color.blue);
colorComboBox.setEditable(true)

我想显示toString()不是你想要的,所以你应该创建一个自定义的单元格渲染器。 http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer

自定义组合框单元格渲染器的示例:

class ColorComboBoxRenderer extends JLabel
        implements ListCellRenderer {

    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {

        if (value instanceof Color) {
            Color color = (Color) value;

            if (color.equals(Color.red)) {
                setText("Red");
            } else if (color.equals(Color.green)) {
                setText("Green");
            }
        } else {
            setText(" ");
        }
        return this;
    }
}

找到颜色对象的实际名称的逻辑当然可以更高级,但你明白了。然后,您创建该类的实例并将其添加到ComboBox

ColorComboBoxRenderer renderer = new ColorComboBoxRenderer ();
colorComboBox.setRenderer(renderer);