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
Componentthat can be used to draw the cell given the five variables passed in. TheJListvariable is a callback reference to the list itself. The object represented byvalueis the object in the list data that this cell corresponds to. The index of the cell in the list is given by the variableindex.isSelectedtells the renderer if the cell has been selected, andcellHasFocustells the renderer if the cell currently has the input focus.
Note
Occasionally, Swing can call this method with an index of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access