
92
|
Chapter 2, Lists and Combos
#19 Turn Methods into List Renderers
HACK
setting a flag so that the cell renderer applies only the colorized foreground
and background colors to that cell.
H A C K
#19
Turn Methods into List Renderers Hack #19
By using a little bit of reflection, you can make a generic ListCellRenderer
that can render data using any method at runtime.
JLists, like JTable and JTree, use a decorator pattern to customize how they
look. This system of cell renderers works well, but it can require you to
build a unique renderer class for each type of object you want to put into
your lists. Often, all you really want to do is call a particular method on the
objects in your list, but writing a complete class to just call one method is a
lot of work for such a small task. This hack shows you how to use reflection
to create a generic cell renderer that can be reused on any object without
subclassing.
Building a Generic Renderer
The default JList cell renderer will just call toString( ) on the objects in the
list and draw the resulting string to the screen. This is fine for simple uses
where you really are just looking at a list of strings or objects with appropri-
ate
toString( ) methods. More complicated applications—and they all
become more complicated eventually—require more complicated objects,
and those objects might not have a convenient or useful
toString( ) method.
Eventually, you have to ...