Home > Articles

Sortable Swing JTable

  • Print
  • + Share This
Sorting a table by one of the columns seems like a capability that should be in any API that displays a table. Although the Swing API does not include this functionality by default, Sun did add the ability to sort a table in a piece of sample code. It's easy, says Marcus Zarra, who walks you though how to add sorting to an existing table model.

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.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.