• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTableで行を選択
#navi(../)
*JTableで行を選択 [#jeb5f621]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-05-24~
更新日:&lastmod;

#contents

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

#screenshot

**サンプルコード [#f054e87d]
#code{{
 JTable t = table;
 t.setRowSelectionAllowed(true);
 t.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
 t.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
   public void valueChanged(ListSelectionEvent e) {
     if(e.getValueIsAdjusting()) return;
     String str = "";
     if(t.getSelectedRowCount()==1) {
       str = getInfo(sorter.modelIndex(t.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+" )";
 }
JTable t = table;
t.setRowSelectionAllowed(true);
t.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
t.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
  public void valueChanged(ListSelectionEvent e) {
    if(e.getValueIsAdjusting()) return;
    String str = "";
    if(t.getSelectedRowCount()==1) {
      str = getInfo(sorter.modelIndex(t.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+" )";
}
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#b6b30ce9]
マウスやカーソルキー、タブキーでの選択状態の変更に対応する場合は、JTableにMouseListenerリスナーを設定するのではなく、JTable#getSelectionModelメソッドでListSelectionModelを参照し、このモデルにListSelectionListenerリスナーを追加して利用します。

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

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