• category: swing folder: RestoreTableColumnOrder title: JTableのTableColumnの表示順を初期状態に戻す tags: [JTable, JTableHeader, TableColumn, TableColumnModel] author: aterai pubdate: 2016-10-03T00:51:19+09:00 description: JTableのTableColumnの表示順が入れ替えられていた場合、それを初期状態(モデル順)に戻します。 image: https://drive.google.com/uc?export=view&id=1uR48L0Uvm0mBLPOYXx8IR1VJYp0KVzuiAQ

概要

JTableTableColumnの表示順が入れ替えられていた場合、それを初期状態(モデル順)に戻します。

サンプルコード

TableColumnModel m = table.getColumnModel();
if (m instanceof SortableTableColumnModel) {
    ((SortableTableColumnModel) m).restoreColumnOrder();
}
//...
class SortableTableColumnModel extends DefaultTableColumnModel {
  public void restoreColumnOrder() {
    Collections.sort(
        tableColumns,
        Comparator.comparingInt(TableColumn::getModelIndex));
    fireColumnMoved(new TableColumnModelEvent(this, 0, tableColumns.size()));
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、DefaultTableColumnModelprotected Vector<TableColumn> tableColumns;TableColumnのモデル・インデックス(TableColumn#getModelIndex()で取得可能)で直接ソートすることで、入れ替え前の初期状態を復元しています。

  • tableColumnsprotectedなので、ソートはDefaultTableColumnModelを継承するクラス内で実行する
    • JTable#createDefaultColumnModel()をオーバーライドしてこのTableColumnModelを使用する
    • ソート後、fireColumnMoved(...)TableColumnの移動を通知し、再描画を実行する必要がある
  • 直接tableColumnsをソートするのではなく、以下のようにTableColumnModel#moveColumn(...)メソッドなどを使用してソートする方法もある
public static void sortTableColumn(TableColumnModel model) {
  //selection sort
  int n = model.getColumnCount();
  for (int i = 0; i < n - 1; i++) {
    TableColumn c = (TableColumn) model.getColumn(i);
    for (int j = i + 1; j < n; j++) {
      TableColumn p = (TableColumn) model.getColumn(j);
      if (c.getModelIndex() - p.getModelIndex() > 0) {
        model.moveColumn(j, i);
        i -= 1;
        break;
      }
    }
  }
}

コメント