List Cell Renderers


  • A cell renderer can be any object that implements the getListCellRendererComponent() method.
  • The list or combo box calls that method for each item in the list, and uses the returned component's paint() method to render the list item.
  • The default cell renderer simply extends JLabel and returns itself, suitably configured, as the cell renderer.
JLabel
+ setBackground(Color)
+ setForeground(Color)
+ setIcon(Icon)
+ setText(String)
+ setEnabled(boolean)
+ setFont(Font)
+ setBorder(Border)
+ paint(Graphics)
ListCellRenderer
+ getListCellRendererComponent
         (JList, Object, int, boolean, boolean)
                  : Component
DefaultListCellRenderer
+ getListCellRendererComponent
         (JList, Object, int, boolean, boolean)
                  : Component
CategoryComboBoxCellRenderer
- indentIcon : IndentIcon
+ getListCellRendererComponent
         (JList, Object, int, boolean, boolean)
                  : Component
public class DefaultListCellRenderer extends JLabel
                           implements ListCellRenderer {

    public Component getListCellRendererComponent
                    (JList list, Object value, int index, 
                     boolean selected, boolean hasFocus) {

        setText((value == null) ? "" : value.toString());
        setEnabled(list.isEnabled());
        setFont(list.getFont());
        setBorder((hasFocus) ? focusBorder : noFocusBorder);
        return this;
    }
}


class CategoryComboBoxCellRenderer extends DefaultListCellRenderer {
    private IndentIcon indentIcon = new IndentIcon();

    public Component getListCellRendererComponent
                    (JList list, Object value, int index, 
                     boolean selected, boolean hasFocus) {
        super.getListCellRendererComponent
                    (list, value, index, selected, hasFocus);
        Category category = (Category)value;

        indentIcon.depth = calculateDepth(category);

        setText(category.getName());
        setIcon(indentIcon);
        return this;
    }
}

class IndentIcon implements Icon {
    int depth = 0;
    public void paintIcon(Component c, Graphics g, int x, int y) {
        ChooserIcon.DIR_ICON.paintIcon(c, g, x + depth * 10, y);
    }
    public int getIconWidth() {
        return icon.getIconWidth() + depth * space;
    }
    public int getIconHeight() {
        return icon.getIconHeight();
    }
}