• 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

概要

JTableで、行を選択した場合の動作をテストします。

サンプルコード

table = new JTable(model);
table.setAutoCreateRowSorter(true);
#spandel
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#spanend
  @Override public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) {
      return;
    }
    int sc = table.getSelectedRowCount();
    changeInfoPanel((sc == 1) ? getInfo() : " ");
#spanadd
table.getSelectionModel().addListSelectionListener(e ->
#spanend
  if (e.getValueIsAdjusting()) {
    return;
  }
  int sc = table.getSelectedRowCount();
  changeInfoPanel((sc == 1) ? getInfo() : " ");
});
#spandel
//...
#spanend
#spanadd
// ...
#spanend
private String getInfo() {
  int index = table.convertRowIndexToModel(table.getSelectedRow());
  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);
}
View in GitHub: Java, Kotlin

解説

マウス、カーソルキー、Tabキーでの選択状態の変更に対応するために、JTableMouseListenerリスナーを設定するのではなく、JTable#getSelectionModelメソッドでListSelectionModelを参照し、このモデルにListSelectionListenerリスナーを追加して利用します。 上記のサンプルでは、マウス、カーソルキー、Tabキーでの選択状態の変更に対応するため、JTableMouseListenerリスナーを設定するのではなくJTable#getSelectionModelメソッドでListSelectionModelを参照し、このモデルにListSelectionListenerリスナーを追加しています。 ListSelectionEvent#getValueIsAdjusting()メソッドでイベントが重複処理を起こさないように制御しています。
  • ListSelectionEvent#getValueIsAdjusting()メソッドでイベントが重複処理を起こさないよう設定

参考リンク

コメント