List Cell Renderers

JList widgets display Objects...

+ JList(Object[])
+ setListData(Object[])
+ getSelectedValue() : Object
+ getSelectedValues() : Object[]
+ isSelectionEmpty() : boolean
... more
class Weight {
    int weight;

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

...using List Cell Renderers.

« Interface »
+ getListCellRendererComponent
      (JList, Object, int, boolean, boolean) : Component
  1. JList gets an object from the list data, and passes it to the cell renderer.
  2. The cell renderer returns a component configured to render the object.
  3. JList calls the component's paint method to render a list cell for that object.
A single component is used to "stamp out" every object in the entire list.
class SimpleCellRenderer extends JLabel 
                        implements ListCellRenderer {
    public SimpleCellRenderer() {

    public Component getListCellRendererComponent(
                 JList   list, 
                 Object  value, 
                 int     index, 
                 boolean isSelected, 
                 boolean cellHasFocus) {


        setBackground(isSelected ? Color.BLACK : Color.WHITE);
        setForeground(isSelected ? Color.WHITE : Color.BLACK);


        return this;