#navi(../)
*JTableで行を選択 [#jeb5f621]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-05-24~
更新日:&lastmod;

#contents
**概要 [#f064647c]
JTableで、行を選択した場合の動作をテストします。

http://terai.xrea.jp/swing/rowselection/screenshot.png

**サンプルコード [#f054e87d]
 tbl.setRowSelectionAllowed(true);
 tbl.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
 tbl.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
   public void valueChanged(ListSelectionEvent e) {
     if(e.getValueIsAdjusting()) return;
     int sc = tbl.getSelectedRowCount();
     String str;
     if(sc<=0 || sc>1) {
       str = "";
     }else{
       str = getInfo(sorter.modelIndex(tbl.getSelectedRow()));
     }
     changeInfoPanel(str);
   }
 });

 private String getInfo(int index) {
   String name = (String)model.getValueAt(index, 1);
   String comment = (String)model.getValueAt(index, 2);
   return name+"( "+comment+" )";
 }

-[[サンプルを起動>http://terai.xrea.jp/swing/rowselection/sample.jnlp]]
-[[jarファイル>http://terai.xrea.jp/swing/rowselection/sample.jar]]
-[[ソース>http://terai.xrea.jp/swing/rowselection/src.zip]]
**解説 [#b6b30ce9]
マウスやカーソルキー、タブキーでの選択状態の変更に対応する場合は、JTableにMouseListenerリスナーを設定するのではなく、JTable#getSelectionModelメソッドでListSelectionModelを参照し、このモデルにListSelectionListenerリスナーを追加して利用します。

ListSelectionEvent#getValueIsAdjusting()メソッドでイベントが重複処理を起こさないように制御しています。

//**参考リンク
**コメント [#r27a6181]
#comment