
Let Your JTables Do the Sorting #23
Chapter 3, Tables and Trees
|
115
HACK
This caches the comparators, but only one is used for sorting at any given
time. In
setSortColumn( ), you cache the index of the sort column, but then
you need to pull up the corresponding
Comparator
. Set the
comparator
—the
one that will be used to perform the sort—to
null
, and then check the com-
parators list to see if there is a
Comparator
at the given index. If so, it will
become the new
comparator
.
Now, you’re ready to handle the sorting. When you need to sort, either
because the sort index has changed or because the underlying model has
changed, you call the
resort( )
method, shown in Example 3-7.
This starts by resetting the size of the
sortedIndicies array, which will be
wrong if the number of rows in the
delegatedModel has changed. Next, build
up an array list of
SortingDelegates, an inner class containing a value from
the
delegatedModel (in the column to be sorted) and a mapped row number.
This class is shown in Example 3-8.
Example 3-7. Resorting based on the current comparator
protected void resort( ) {
// does sortedIndicies need to grow or shrink?
if (sortedIndicies.length != delegatedModel.getRowCount( )) {
sortedIndicies = new int [delegatedModel.getRowCount( )];
}
// build up a list of SortingDelegates
ArrayList sortMe = new ArrayList( );
for (int i=0; i<delegatedModel.getRowCount( ); i++) {
SortingDelegate sd =
new SortingDelegate ...