Swing/RestoreTableColumnOrder のバックアップ(No.3)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/RestoreTableColumnOrder へ行く。
- 1 (2016-10-03 (月) 00:52:32)
- 2 (2016-10-03 (月) 13:06:19)
- 3 (2017-02-20 (月) 19:40:38)
- 4 (2017-02-28 (火) 17:51:53)
- 5 (2017-11-10 (金) 14:07:45)
- 6 (2018-02-15 (木) 14:23:42)
- 7 (2019-05-22 (水) 19:35:38)
- 8 (2019-06-21 (金) 19:13:55)
- 9 (2021-02-27 (土) 12:45:21)
- 10 (2023-04-30 (日) 12:20:40)
- 11 (2025-01-03 (金) 08:57:02)
- 12 (2025-01-03 (金) 09:01:23)
- 13 (2025-01-03 (金) 09:02:38)
- 14 (2025-01-03 (金) 09:03:21)
- 15 (2025-01-03 (金) 09:04:02)
- 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
概要
JTable
のTableColumn
の表示順が入れ替えられていた場合、それを初期状態(モデル順)に戻します。
Screenshot

Advertisement
サンプルコード
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解説
上記のサンプルでは、DefaultTableColumnModel
のprotected Vector<TableColumn> tableColumns;
をTableColumn
のモデル・インデックス(TableColumn#getModelIndex()
で取得可能)で直接ソートすることで、入れ替え前の初期状態を復元しています。
tableColumns
はprotected
なので、ソートは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;
}
}
}
}