
Building a Drop-Down Menu Button #10
Chapter 1, Basic JComponents
|
43
HACK
H A C K
#10
Building a Drop-Down Menu Button
Hack #10
This hack shows how to build a color chooser as a proper drop-down
component. It will behave like
JComboBox but without the extension
headaches of Sun’s version of the class.
Most custom Swing components are created with simple subclasses of the
standard base classes in
javax.swing
. This works fine most of the time, but
every now and then you need to build something where there is no easy
standard component to start with. Even worse, sometimes the obvious
choice for your starting point is a component so convoluted that you can’t
figure out where to start. Still, you’d rather not reimplement the wheel. No,
I’m not talking about
JTree or JTable—I’m referring to the JComboBox. It
seems like such a simple component, but the implementation is fiendishly
complex.
Most large applications use components that feel like the
JComboBox, but do
something entirely different, like select a color or show a history list. A quick
search through the
JComboBox API doesn’t turn up any obvious extension
points. You could customize it with some cell renderers, but if you need a
component that doesn’t show a list of data, you are pretty much out of luck.
The source to
JComboBox is not very helpful either. The work is spread out
over several UI classes in the various Look and Feel (L&F) packages. If you
did ...