• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTableで行を選択
#navi(../)
#tags(JTable, ListSelectionListener)
RIGHT:Posted by &author(aterai); at 2004-05-24
*JTableで行を選択 [#jeb5f621]
``JTable``で、行を選択した場合の動作をテストします。
---
category: swing
folder: RowSelection
title: JTableで行を選択
tags: [JTable, ListSelectionListener]
author: aterai
pubdate: 2004-05-24T05:21:46+09:00
description: JTableで、行を選択した場合の動作をテストします。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTSWRoWNRI/AAAAAAAAAio/X-jqAVKs3Bw/s800/RowSelection.png
---
* 概要 [#summary]
`JTable`で、行を選択した場合の動作をテストします。

-&jnlp;
-&jar;
-&zip;
#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTSWRoWNRI/AAAAAAAAAio/X-jqAVKs3Bw/s800/RowSelection.png)

//#screenshot
#ref(http://lh4.ggpht.com/_9Z4BYR88imo/TQTSWRoWNRI/AAAAAAAAAio/X-jqAVKs3Bw/s800/RowSelection.png)

**サンプルコード [#f054e87d]
* サンプルコード [#sourcecode]
#code(link){{
table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
  @Override public void valueChanged(ListSelectionEvent e) {
    if(e.getValueIsAdjusting()) return;
    int sc = table.getSelectedRowCount();
    changeInfoPanel((sc==1)?getInfo():" ");
table.getSelectionModel().addListSelectionListener(e ->
  if (e.getValueIsAdjusting()) {
    return;
  }
  int sc = table.getSelectedRowCount();
  changeInfoPanel((sc == 1) ? getInfo() : " ");
});
//...
// ...
private String getInfo() {
  int index = table.convertRowIndexToModel(table.getSelectedRow());
  String name = (String)model.getValueAt(index, 1);
  String comment = (String)model.getValueAt(index, 2);
  return name+"( "+comment+" )";
  String str = (String) model.getValueAt(index, 0);
  Integer idx = (Integer) model.getValueAt(index, 1);
  Boolean flg = (Boolean) model.getValueAt(index, 2);
  return String.format("%s, %d, %s", str, idx, flg);
}
}}

**解説 [#b6b30ce9]
マウス、カーソルキー、KBD{TAB}キーでの選択状態の変更に対応するために、``JTable``に``MouseListener``リスナーを設定するのではなく、``JTable#getSelectionModel``メソッドで``ListSelectionModel``を参照し、このモデルに``ListSelectionListener``リスナーを追加して利用します。
* 解説 [#explanation]
上記のサンプルでは、マウス、カーソルキー、KBD{Tab}キーでの選択状態の変更に対応するため、`JTable`に`MouseListener`リスナーを設定するのではなく`JTable#getSelectionModel`メソッドで`ListSelectionModel`を参照し、このモデルに`ListSelectionListener`リスナーを追加しています。

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

//**参考リンク
**コメント [#r27a6181]
- ありがとう。助かります。 -- [[ごん]] &new{2009-10-16 (金) 19:37:37};
-- どうもです。 -- [[aterai]] &new{2009-10-17 (土) 00:09:01};
- どうもです。  -- [[ごん?]] &new{2011-08-02 (火) 15:31:26};
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTable.html#getSelectionModel-- JTable#getSelectionModel() (Java Platform SE 8)]

* コメント [#comment]
#comment
- ありがとう。助かります。 -- &user(ごん); &new{2009-10-16 (金) 19:37:37};
-- どうもです。 -- &user(aterai); &new{2009-10-17 (土) 00:09:01};
- どうもです。  -- &user(ごん?); &new{2011-08-02 (火) 15:31:26};

#comment