开发者

Java Custom ListCellRenderer casting problem (SSCCE included)

I am trying to create a custom ListCellRenderer in order to give different foreground colors in each line, depending on the input of the jList. I am not an expert or anything, but I really can't figure this out.

I get a casting error:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to app.CustomObject

Thanks for your time.

Here is the 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;
   开发者_C百科 }

    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();
    }
}


CustomObject o = (CustomObject) value;

value here appears to be a plain String ("Option1" maybe?), not a CustomObject.

If you want it to be a CustomObject, you might try something like this in your main:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜