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());
        }
    }
});
Share:
33,414
user3057184
Author by

user3057184

Updated on December 03, 2020

Comments

  • user3057184
    user3057184 over 3 years

    I need the right AcionListener for my JTable.

    At program start there is no row selected by default. If I now select any row in this JTable then the ActionListener shall start.

  • kleopatra
    kleopatra over 10 years
    basically correct, though: a) in a real-world context you most probably would want to check for isValueAdjusting b) the value might be null
  • mKorbel
    mKorbel over 10 years
    the value might be null, she means to test if(selectedRow > -1), required, otherwise you can to kill JTables view with endless loop from exceptions that can freeze Swing GUI
  • Paul Samsotha
    Paul Samsotha over 10 years
    Thanks, I've added that to the answer.
  • kleopatra
    kleopatra over 10 years
    @mKorbel good catch - but yet another than I meant :-)
  • onlyforthis
    onlyforthis almost 9 years
    Where should i place this? In the main of the Jframe class or somewhere else?
  • Ankit Kumar Singhal
    Ankit Kumar Singhal about 7 years
    This worked for me.