Implementing a Column Model

Here’s a custom column model that keeps all of its columns in alphabetical order as they are added:

// SortingColumnModel.java
// A simple extension of the DefaultTableColumnModel class that sorts 
// incoming columns
//
import javax.swing.table.*;

public class SortingColumnModel extends DefaultTableColumnModel {

  public void addColumn(TableColumn tc) {
    super.addColumn(tc);
    int newIndex = sortedIndexOf(tc);
    if (newIndex != tc.getModelIndex( )) {
      moveColumn(tc.getModelIndex( ), newIndex);
    }
  }

  protected int sortedIndexOf(TableColumn tc) {
    // Just do a linear search for now.
    int stop = getColumnCount( );
    String name = tc.getHeaderValue( ).toString( );

    for (int i = 0; i < stop; i++) {
      if (name.compareTo(getColumn(i).getHeaderValue( ).toString( )) <= 0) {
        return i;
      }
    }
    return stop;
  }
}

Implementing the model is simple. We override addColumn( ) to add the column to the superclass and then move it into the appropriate position. You can use this column model with any data model. The next section goes into much more detail on the table model used to store the real data, so for this simple example, we’ll use the DefaultTableModel class to hold the data. Once we have our table model and our column model, we can build a JTable with them. Then, any columns we add are listed in alphabetical order (by the header), regardless of the order in which they were added. The result looks like Figure 15-4.

Figure 15-4. A sorting column model; the columns are sorted by name as they ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.