
Create a Collections-Aware JComboBox #20
Chapter 2, Lists and Combos
|
95
HACK
Using toString( ) on the strings will be the same as the default renderer,
simply drawing Proton, Neutron, and Electron in the list (see Figure 2-12).
The resulting change would look like Figure 2-13.
Using reflection for cell renderers is a very powerful concept because you
can reuse potentially complicated code with very little additional effort.
Using it to display strings is just a trivial example. Imagine you had a bunch
of objects representing entries from an RSS feed. Instead of creating a cus-
tom renderer or wrapping the entries in objects with a custom
toString( )
method, you could use the GenericListCellRenderer with getTitle( ) to
automatically call the
getTitle( ) method on the entry objects—no new
subclasses or extra code. Just a single string and the renderer takes care of
the rest. That is the power of reflection.
H A C K
#20
Create a Collections-Aware JComboBox Hack #20
You’ve moved on from Vector; your combo boxes should, too.
JComboBox is one of Swing’s oldest components. Unfortunately, it accepts
arrays of objects and
Vectors only. Now that Collections objects like List
have been part of the JDK for years, it would be nice to use them directly in
a combo box without shuffling objects in and out of arrays. Fortunately, the
JComboBox uses an MVC (Model-View-Controller) architecture, so you can
solve this problem ...