
110
|
Chapter 3, Tables and Trees
#23 Let Your JTables Do the Sorting
HACK
H A C K
#23
Let Your JTables Do the Sorting Hack #23
Why doesn’t Swing already offer this? Oh well, here’s how to do it yourself.
It’s hard to imagine you’ll do much serious work with JTables without need-
ing to sort the contents by one of the columns, or support changing between
columns to use as the sort criteria. In fact, given how generous the Swing
API usually is, it’s kind of surprising that it doesn’t already offer it. Oh well,
it’s not that hard to do for yourself.
There are a couple of approaches you could take to solve this problem. You
could create a subclass of
TableModel, one that keeps an internal Comparator
to do the sorting and resorts every time an add( ) or remove( ) type method is
called. The drawback to this approach is choosing which of the model
classes to subclass. If you go too high up the hierarchy by implementing
TableModel or subclassing DefaultTableModel, you would miss some typical
Swing functionality that developers expect, like the ability to add and
remove rows provided by
DefaultMutableTableModel. On the other hand, if
you subclass
DefaultMutableTableModel, other developers will be unhappy
because subclassing your class requires them to pick up public
add( ) and
delete( ) type methods that expose their data in ways they don’t want.
So, consider an alternative: two table models, one that the
JTable