TITLE:TableRowSorterのSortKeysをクリアする
#navi(../)
*TableRowSorterのSortKeysをクリアする [#q8dd9a10]
Posted by [[terai]] at 2007-08-27

#contents

**概要 [#b606e1ce]
JDK 6 で導入されたTableRowSorterでの行ソートを、テーブルヘッダの「Shift+クリック」でクリアします。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#o4d0be64]
#code{{
table.setAutoCreateRowSorter(true);
table.getTableHeader().addMouseListener(new MouseAdapter() {
  @Override public void mouseClicked(MouseEvent e) {
    final RowSorter<? extends TableModel> sorter = table.getRowSorter();
    if(sorter==null || sorter.getSortKeys().size()==0) return;
    JTableHeader h = (JTableHeader)e.getComponent();
    TableColumnModel columnModel = h.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    if(viewColumn<0) return;
    int column = columnModel.getColumn(viewColumn).getModelIndex();
    if(column != -1 && e.isShiftDown()) {
      EventQueue.invokeLater(new Runnable() {
        @Override public void run() {
          sorter.setSortKeys(null);
        }
      });
    }
  }
});
}}

**解説 [#sc19e708]
ヘッダにマウスリスナーを設定し、Shiftキーを押しながらのクリックの場合は、TableRowSorter#setSortKeysメソッドを使って、ソートキーを空にしています。

上記のサンプルでは、以下のような制限があります。
-ソートキーになっていないヘッダカラムをShift+クリックした場合でも、ソート状態をクリアする
-%%行がソートされている場合は、ドラッグ&ドロップで行を入れ替え不可%% D&D機能は削除

**参考リンク [#zd14dfcb]
-[[TableSorter.java>http://java.sun.com/docs/books/tutorial/uiswing/examples/components/TableSorterDemoProject/src/components/TableSorter.java]]

**コメント [#fc73f66f]
#comment