Java Custom ListCellRenderer强制转换问题(包括SSCCE)

时间:2010-06-24 02:39:08

标签: java casting listcellrenderer

我正在尝试创建一个自定义ListCellRenderer,以便在每一行中提供不同的前景色,具体取决于jList的输入。我不是专家或任何东西,但我真的无法弄清楚这一点。

我收到了投射错误:

线程“main”中的异常java.lang.ClassCastException:java.lang.String无法强制转换为app.CustomObject

感谢您的时间。

这是SSCCE:

import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

public class MyListCellRenderer extends DefaultListCellRenderer
{

    static Color color;
    static ListSelectionModel listSelectionModel;
    static JList jList1;
    static DefaultListModel listModel = new DefaultListModel();
    static JFrame frame;

    @Override
    public Component getListCellRendererComponent(JList list,
            Object value, int index, boolean isSelected,
            boolean cellHasFocus)
    {
        super.getListCellRendererComponent(list,
                value,
                index,
                isSelected,
                cellHasFocus);

        if (value != null)
        {
            CustomObject o = (CustomObject) value;
            setText(o.getData());
            setForeground(o.getColor());
        }
        return this;
    }

    public static void main(String[] args)
    {


        jList1 = new javax.swing.JList();
        listSelectionModel = jList1.getSelectionModel();
        listSelectionModel.addListSelectionListener(
                new app.ListSelectionHandler());
        jList1.setCellRenderer(new app.MyListRenderer());
        jList1.setModel(listModel);
        listModel.addElement("Option1");

        frame = new JFrame();
        frame.add(jList1);
        frame.pack();
        frame.setVisible(true);
    }
}

class CustomObject
{

    String s;
    Color color;

    public CustomObject(Color color, String s)
    {
        this.s = s;
        this.color = color;
    }

    public Color getColor()
    {
        return color;
    }

    public String getData()
    {
        return s;
    }

    @Override
    public String toString()
    {
        return s + color.getRGB();
    }
}

1 个答案:

答案 0 :(得分:1)

CustomObject o = (CustomObject) value;

value此处似乎是普通String"Option1"可能?),而不是CustomObject

如果您希望它是CustomObject,您可以在main中尝试这样的事情:

listModel.addElement(new CustomObject(Color.BLUE, "Option1"));