简体   繁体   中英

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

    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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM