• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:TableRowSorterのSortKeysをクリアする
#navi(../)
#tags(JTable, TableRowSorter, MouseListener)
RIGHT:Posted by &author(aterai); at 2007-08-27
*TableRowSorterのSortKeysをクリアする [#q8dd9a10]
``JDK 6``で導入された``TableRowSorter``での行ソートを、テーブルヘッダの``Shift``+クリックでクリアします。
---
title: TableRowSorterのSortKeysをクリアする
tags: [JTable, TableRowSorter, MouseListener]
author: aterai
pubdate: 2007-08-27T12:33:13+09:00
description: JDK 6で導入されたTableRowSorterでの行ソートを、テーブルヘッダのKBD{Shift}+クリックでクリアします。
---
* 概要 [#q8dd9a10]
`JDK 6`で導入された`TableRowSorter`での行ソートを、テーブルヘッダのKBD{Shift}+クリックでクリアします。

-&jnlp;
-&jar;
-&zip;
#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTJF8YbgvI/AAAAAAAAAT0/NDSO1fqmVNw/s800/ClearSortingState.png)

//#screenshot
#ref(http://lh3.ggpht.com/_9Z4BYR88imo/TQTJF8YbgvI/AAAAAAAAAT0/NDSO1fqmVNw/s800/ClearSortingState.png)

**サンプルコード [#o4d0be64]
* サンプルコード [#o4d0be64]
#code(link){{
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``メソッドを使って、ソートキーを空にしています。
* 解説 [#sc19e708]
ヘッダにマウスリスナーを設定し、KBD{Shift}キーを押しながらのクリックの場合は、`TableRowSorter#setSortKeys`メソッドを使って、ソートキーを空にしています。

上記のサンプルでは、以下のような制限があります。

-ソートキーになっていないヘッダカラムを``Shift``+クリックした場合でも、ソート状態をクリアする
-%%行がソートされている場合は、ドラッグ&ドロップで行を入れ替え不可%% ``D&D``機能は削除
- ソートキーになっていないヘッダカラムをKBD{Shift}+クリックした場合でも、ソート状態をクリアする
- %%行がソートされている場合は、ドラッグ&ドロップで行を入れ替え不可%% `D&D`機能は削除

**参考リンク [#zd14dfcb]
-[http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableSorterDemoProject/src/components/TableSorter.java TableSorter.java]
-[[TableRowSorterでJTableのソート>Swing/TableRowSorter]]
-[[TableRowSorterのソートをヘッダクリックで昇順、降順、初期状態に変更>Swing/TriStateSorting]]
* 参考リンク [#zd14dfcb]
- [http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableSorterDemoProject/src/components/TableSorter.java TableSorter.java]
- [[TableRowSorterでJTableのソート>Swing/TableRowSorter]]
- [[TableRowSorterのソートをヘッダクリックで昇順、降順、初期状態に変更>Swing/TriStateSorting]]

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