Java Reference
In-Depth Information
In order to sort, you need to maintain a mapping of the real data to the sorted data. From
the user interface, you must allow the user to select a column header label to enable sorting of
a particular column.
To use the sorting capabilities, you tell the custom
TableSorter
class about your data
model, decorate it, and create a
JTable
from your decorated model instead of the original. To
enable the sorting by picking column header labels, you need to call the custom
install()
method of the
TableHeaderSorter
class shown in the following source code for the
TableSorter
class:
TableSorter sorter = new TableSorter(model);
JTable table = new JTable(sorter);
TableHeaderSorter.install(sorter, table);
The main source code for the
TableSorter
class is shown in Listing 18-6. It extends from
the
TableMap
class, which is shown in Listing 18-7. The
TableSorter
class is where all the action
is. The class does the sorting and notifies others that the data has changed.
Listing 18-6.
Table Column Sorting
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.*;
public class TableSorter extends TableMap implements TableModelListener {
int indexes[] = new int[0];
Vector sortingColumns = new Vector();
boolean ascending = true;
public TableSorter() {
}
public TableSorter(TableModel model) {
setModel(model);
}
public void setModel(TableModel model) {
super.setModel(model);
reallocateIndexes();
sortByColumn(0);
fireTableDataChanged();
}
public int compareRowsByColumn(int row1, int row2, int column) {
Class type = model.getColumnClass(column);
TableModel data = model;