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