javaswingjtablelistselectionlistener

Error when delete row from Jtable


My Jtable have a listSelectionListener :

jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            System.out.println(jTable1.getValueAt(jTable1.getSelectedRow(), 0));
        }
    });

i create a button to delete all rows of Jtable with event:

for (int i =jTable1.getModel().getRowCount()-1; i >=0 ; i--) {
        ((DefaultTableModel)jTable1.getModel()).removeRow(i);
    }

If i press the button without choosing any row ,there is no error but when i choose a row then press the button i get this error:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1

This don't happen when table don't have ListSelectionListener. Where do i wrong?

Thanks in advance for help with this.


Solution

  • This don't happen when table don't have ListSelectionListener

    So I'm guessing that your code to remove all the rows in the table executes. As the rows are removed the row selection must change since there are no longer any rows to select.

    System.out.println(jTable1.getValueAt(jTable1.getSelectedRow(), 0));
    

    Then the above statement is executed and the getSelectedRow() method return -1 which causes the Exception. Try:

    int selectedRow = jTable1.getSelectedRow();
    System.out.println("Selected Row: " + selectedRow;
    
    if (selectedRow != -1)
        System.out.println(jTable1.getValueAt(selectedRow, 0));