O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 to register a class that implements the ListCellRenderer interface. This registration can be done with the setCellRenderer( ) 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 argument is a reference to the list itself. value is the object within the list data that will be drawn in this cell. The index of the cell in the list is given by the argument index. isSelected tells the renderer if the cell is currently selected, and cellHasFocus tells the renderer if the cell currently has the input focus.

Tip

Occasionally, Swing calls this method with an index of -1, which is, of course, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required