Displaying Cell Elements

Swing gives the programmer the option to specify how each element in the list (called a cell ) should be displayed on the screen. The list itself maintains a reference to a cell renderer. Cell renderers are common in Swing components, including lists and combo boxes. Essentially, a cell renderer is a component whose paint() method is called each time the component needs to draw or redraw an element. To create a cell renderer, you need only register a class that extends the ListCellRenderer interface. This registration can be done with the setCell-Renderer() method of JList or JComboBox:

JList list = new JList();
list.setCellRenderer(new myCellRenderer());

The ListCellRenderer Interface

The ListCellRenderer interface must be implemented by cell renderers for lists and combo boxes. It has only one method.

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

This method must return a Component that can be used to draw the cell given the five variables passed in. The JList variable is a callback reference to the list itself. The object represented by value is the object in the list data that this cell corresponds to. The index of the cell in the list is given by the variable index. isSelected tells the renderer if the cell has been selected, and cellHasFocus tells the renderer if the cell currently has the input focus.

Note

Occasionally, Swing can call this method with an index of ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.