spqa
spqa

Reputation: 186

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.

Upvotes: 0

Views: 613

Answers (2)

camickr
camickr

Reputation: 324137

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));

Upvotes: 0

Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4418

Can you try with this?

DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);

Upvotes: 1

Related Questions