import java.awt.*;
import java.util.Vector;
import javax.swing.*;
public class MyFrame extends JFrame
{
private JList list;
public MyFrame()
{
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector data = new Vector();
data.add(new ListElement("aaa", Color.RED));
data.add(new ListElement("bbb", Color.GREEN));
data.add(new ListElement("ccc", Color.BLUE));
data.add(new ListElement("ddd", Color.YELLOW));
this.list = new JList(new MyListModel( data ));
this.list.setCellRenderer(new DefaultListCellRenderer()
{
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
Component comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
MyListModel model = (MyListModel) list.getModel(); // Model aus Liste holen und entsprechend casten
ListElement element = model.getListElementAt(index); // Element aus Model holen
Color color = element.getColor(); // aktuelles Colorobjekt aus Element holen
comp.setForeground( color ); // Colorobjekt uebergeben
//comp.setForeground( ((ListElement ) ((MyListModel) list.getModel()).getListElementAt( index )).getColor() );
return comp;
}
});
// ###################################################
// #### add new data
Vector newData = new Vector();
newData.add(new ListElement("eee", Color.YELLOW));
newData.add(new ListElement("fff", Color.GREEN));
newData.add(new ListElement("ggg", Color.RED));
newData.add(new ListElement("hhh", Color.YELLOW));
((MyListModel)this.list.getModel()).setData( newData );
// ##################################################
this.getContentPane().add( new JScrollPane( list) );
this.setVisible(true);
}
public static void main(String[] args)
{
new MyFrame();
}
}
class MyListModel extends DefaultListModel
{
private Vector data;
public MyListModel(Vector data)
{
this.data = data;
}
public void setData(Vector data)
{
this.data = data;
this.fireContentsChanged(this, 0, this.data.size());
}
public Object getElementAt(int index)
{
return ((ListElement)this.data.get( index )).getValue();
}
public ListElement getListElementAt(int index)
{
return (ListElement) this.data.get( index );
}
public int getSize()
{
return this.data.size();
}
}
class ListElement
{
private Color color;
private Object value;
public ListElement(Object value, Color color)
{
this.value = value;
this.color = color;
}
public Color getColor()
{
return color;
}
public Object getValue()
{
return value;
}
public void setColor(Color color)
{
this.color = color;
}
public void setValue(Object object)
{
value = object;
}
public String toString()
{
return this.value.toString();
}
}