Swing/RowSelection のバックアップの現在との差分(No.8)
TITLE:JTableで行を選択
JTableで行を選択
編集者:Terai Atsuhiro~
作成日:2004-05-24
更新日:2024-03-30 (土) 23:38:46
概要
JTable
で、行を選択した場合の動作をテストします。
Screenshot
Advertisement
概要
JTableで、行を選択した場合の動作をテストします。サンプルコード
#spanend
#spanadd
table = new JTable(model);
#spanend
#spanadd
table.setAutoCreateRowSorter(true);
#spanend
#spanadd
table.getSelectionModel().addListSelectionListener(e ->
#spanend
if (e.getValueIsAdjusting()) {
return;
}
int sc = table.getSelectedRowCount();
changeInfoPanel((sc == 1) ? getInfo() : " ");
#spanadd
});
#spanend
#spanadd
// ...
#spanend
#spanadd
private String getInfo() {
#spanend
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);
#spanadd
}
#spanend
#spanadd
View in GitHub: Java, Kotlin#screenshot
解説
上記のサンプルでは、マウス、カーソルキー、Tabキーでの選択状態の変更に対応するため、JTable
にMouseListener
リスナーを設定するのではなくJTable#getSelectionModel
メソッドでListSelectionModel
を参照し、このモデルにListSelectionListener
リスナーを追加しています。
サンプルコード
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+" )"; }
-
ListSelectionEvent#getValueIsAdjusting()
メソッドでイベントが重複処理を起こさないよう設定
- &jnlp;
- &jar;
- &zip;
参考リンク
解説
マウスやカーソルキー、タブキーでの選択状態の変更に対応する場合は、JTableにMouseListenerリスナを設定するのではなく、JTable#getSelectionModelメソッドでListSelectionModelを参照し、このモデルにListSelectionListenerリスナを追加して利用します。コメント
- ありがとう。助かります。 -- ごん
- どうもです。 -- aterai
- どうもです。 -- ごん?