我正在尝试创建一个自定义 ListCellRenderer,以便根据 jList 的输入在每行中提供不同的前景色。我不是专家或任何东西,但我真的无法弄清楚这一点。
我收到一个铸造错误:
线程“主”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();
}
}