Sortable Swing JTable
Sun has written a large number of helper classes that add to the base functionality of the Java APIs. Although these helpers extend the functionality of the existing API, they are not used so often as to require them to be integrated into those APIs. Therefore, Sun offers them for free to be used by developers as needed. One such helper is the TableSorter class. The original source code for this class can be retrieved from Sun tutorials.
Integration
Integrating this helper class into my existing design (from the previous articles) is extremely simple. First, the original initialization code for my JTable and TableModel (see previous article for the full source code):
public MyFrame() { ... mtm = new MyTableModel(arrayList); JTable temp = initializeTable(); ... } public JTable initializeTable() { JTable _table = new JTable(mtm); ... }
And now the code with the TableSorter integrated in:
public MyFrame() { ... mtm = new MyTableModel(arrayList); JTable temp = initializeTable(); ... } public JTable initializeTable() { TableSorter ts = new TableSorter(mtm); JTable _table = new JTable(ts); ts.setTableHeader(_table.getTableHeader()); ... }
These changes are quite trivial, but add full column sorting to any existing table model. The "trick" that makes this appear so simple on the surface is a matter of wrapping. Sun's TableSorter wraps my existing table model and intercepts all calls to it. As far as my table model is concerned, nothing has changed and it has no knowledge that its calls are getting routed through an intermediary.