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. TheJList
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 argumentindex
.isSelected
tells the renderer if the cell is currently selected, andcellHasFocus
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, ...
Get Java Swing, 2nd Edition 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.