A list uses an object called a cell renderer to display each of its items. The default cell renderer knows how to display strings and icons and it displaysObject
s by invokingtoString
. If you want to change the way the default renderer display icons or strings, or if you want behavior different than what is provided bytoString
, you can implement a custom cell renderer. Take these steps to provide a custom cell renderer for a list:We do not provide an example of a list with a custom cell renderer, but we do have an example of a combo box with a custom renderer — and combo boxes use the same type of renderer as lists. See the example described in Providing a Custom Renderer.
- Write a class that implements the
ListCellRenderer
interface.- Create an instance of your class and call the list's
setCellRenderer
using the instance as an argument.
The List API
The following tables list the commonly usedJList
constructors and methods. Other methods you are most likely to invoke on a JList
object are those such as setPreferredSize
that its superclasses provide. See The JComponent API for tables of commonly used inherited methods. Much of the operation of a list is managed by other objects. The items in the list are managed by a list model object, the selection is managed by a list selection model object, and most programs put a list in a scroll pane to handle scrolling. For the most part, you do not need to worry about the models because JList
creates them as necessary and you interact with them implicitly with JList
's convenience methods.