• 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);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
  @Override public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) {
      return;
    }
    int sc = table.getSelectedRowCount();
    changeInfoPanel((sc == 1) ? getInfo() : " ");
  }
});
//...
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リスナーを追加して利用します。

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

参考リンク

コメント