Default Cell Renderer

The default renderer calls the object's toString() method...

class Weight {
    int weight;

    public Weight(int weight) {
        this.weight = weight;
    }

    public String toString() {
        return weight + " pounds";
    }
}

...but we can plug in our own List Cell Renderer to render the data any way we want.

class RedAlertCellRenderer extends JLabel 
                        implements ListCellRenderer {
    
    public Component getListCellRendererComponent(
                 JList   list, 
                 Object  value, 
                 int     index, 
                 boolean isSelected, 
                 boolean cellHasFocus) {

        setText(value.toString());

        Color weightColor = Color.BLACK;

        if (((Weight) value).weight > 199) {
            weightColor = Color.RED;
        }
        
        setBackground(isSelected ? weightColor : Color.WHITE);
        setForeground(isSelected ? Color.WHITE : weightColor);
        
        setEnabled(list.isEnabled());

        return this;
    }
}
JList
+ JList(Object[])
+ setListData(Object[])
+ getSelectedValue() : Object
+ getSelectedValues() : Object[]
+ isSelectionEmpty() : boolean
+ setCellRenderer(ListCellRenderer)
... more