JTableで行を選択
Total: 42487
, Today: 2
, Yesterday: 4
Posted by aterai at
Last-modified:
Summary
JTable
で、行を選択した場合の動作をテストします。
Screenshot

Advertisement
Source Code Examples
table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.getSelectionModel().addListSelectionListener(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, KotlinExplanation
上記のサンプルでは、マウス、カーソルキー、Tabキーでの選択状態の変更に対応するため、JTable
にMouseListener
リスナーを設定するのではなくJTable#getSelectionModel
メソッドでListSelectionModel
を参照し、このモデルにListSelectionListener
リスナーを追加しています。
ListSelectionEvent#getValueIsAdjusting()
メソッドでイベントが重複処理を起こさないよう設定