Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove selected rows from a JTable?

Tags:

jtable

I've tried this:

public void removeSelectedFromTable(JTable from)
{
    int[] rows = from.getSelectedRows();
    TableModel tm= from.getModel();

    while(rows.length>0)
    {
        ((DefaultTableModel)tm).removeRow(from.convertRowIndexToModel(rows[0]));

        rows = from.getSelectedRows();
    }
    from.clearSelection();
}

But, it sometimes leaves one still there. What can be the problem?

like image 441
Penchant Avatar asked Mar 17 '09 17:03

Penchant


People also ask

How do you clear a JTable row?

If using the DefaultTableModel , just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI. JTable table; … DefaultTableModel model = (DefaultTableModel) table.

How can I tell if a row is selected in JTable?

So you can call table. getSelectionModel(). isSelectionEmpty() to find out if any row is selected.


1 Answers

It doesn't work, this is better:

public void removeSelectedRows(JTable table){
   DefaultTableModel model = (DefaultTableModel) this.table.getModel();
   int[] rows = table.getSelectedRows();
   for(int i=0;i<rows.length;i++){
     model.removeRow(rows[i]-i);
   }
}
like image 109
Alejandro Avatar answered Sep 20 '22 16:09

Alejandro