TITLE:JTableで行を選択
Posted by aterai at 2004-05-24

JTableで行を選択

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

概要

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

サンプルコード

#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
table = new JTable(model);
table.setAutoCreateRowSorter(true);
#spandel
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#spanend
  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 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);
}

解説

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

解説

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

コメント

  • ありがとう。助かります。 -- ごん
    • どうもです。 -- aterai

参考リンク

コメント