JTable - ActionListener for select a row
33,414
Try this. I use a ListSelectionListener
and it works for me. I added a listener to the table Model
jTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
if (jTable.getSelectedRow() > -1) {
// print first column value from selected row
System.out.println(jTable.getValueAt(jTable.getSelectedRow(), 0).toString());
}
}
});
Author by
user3057184
Updated on December 03, 2020Comments
-
user3057184 over 3 years
I need the right
AcionListener
for myJTable
.At program start there is no row selected by default. If I now select any row in this
JTable
then theActionListener
shall start. -
kleopatra over 10 yearsbasically correct, though: a) in a real-world context you most probably would want to check for isValueAdjusting b) the value might be null
-
mKorbel over 10 years
the value might be null
, she means to testif(selectedRow > -1)
, required, otherwise you can to kill JTables view with endless loop from exceptions that can freeze Swing GUI -
Paul Samsotha over 10 yearsThanks, I've added that to the answer.
-
kleopatra over 10 years@mKorbel good catch - but yet another than I meant :-)
-
onlyforthis almost 9 yearsWhere should i place this? In the main of the Jframe class or somewhere else?
-
Ankit Kumar Singhal about 7 yearsThis worked for me.