Penchant
Penchant

Reputation: 1165

How do you remove selected rows from a 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?

Upvotes: 17

Views: 62511

Answers (18)

Dmytro Sokolyuk
Dmytro Sokolyuk

Reputation: 1086

Java 8+ streaming solution:

JTable table;
DefaultTableModel model = (DefaultTableModel) table.getModel();

IntStream.of(table.getSelectedRows())
            .boxed()
            .sorted(Collections.reverseOrder())
            .map(table::convertRowIndexToModel) // support for sorted table
            .forEach(model::removeRow);

Upvotes: 5

prageeth sanjeewa
prageeth sanjeewa

Reputation: 21

try this is perfect work and simple

DefaultTableModel df1 = (DefaultTableModel) jTable1.getModel();
    int rs[] = jTable1.getSelectedRows();
    for (int i = rs.length-1; i >=0 ; i--) {

        int k = rs[i];

        df1.removeRow(k);

    }

Upvotes: 2

Sasha Raskind
Sasha Raskind

Reputation: 41

The stream solution above doesn't take into account sorting, it may be fixed this way:

        IntStream.of(table.getSelectedRows())
            .boxed().map(i -> table.convertRowIndexToModel(i))
            .sorted(Collections.reverseOrder())
            .forEach(((DefaultTableModel)table.getModel())::removeRow);

Upvotes: 0

That works for me:

if(tablaNotif.getSelectedRows().length>0){
    int[] rows = tablaNotif.getSelectedRows();
    if(tablaNotif.getSelectedRows().length<2) {
        modelo.remove(tablaNotif.convertRowIndexToModel(rows[0]));
    } else{
        for(int i = 0; i<tablaNotif.getSelectedRows().length;i++) {
            modelo.remove(tablaNotif.convertRowIndexToModel(rows[i]));
        }
        modelo.remove(tablaNotif.convertRowIndexToModel(rows[(tablaNotif.getSelectedRows().length-1)]));
    }
}

Upvotes: 0

Shalika Ashan
Shalika Ashan

Reputation: 1

The code below will work:

do {
    ((DefaultTableModel) jXTable1.getModel()).removeRow(jXTable1.getSelectedRows()[0]);
} while (jXTable1.getSelectedRowCount() > 0);

Upvotes: 0

NguyenVanSon
NguyenVanSon

Reputation: 1

It is woked for me.enter code here

public void removeSelectedFromTable(JTable from)
    {
        int[] rows = from.getSelectedRows();
        DefaultTableModel tm = (DefaultTableModel) from.getModel();
        for (int i = rows.length-1; i >= 0; i--) {
            tm.removeRow(rows[i]);
        }
}

Upvotes: 0

user1369641
user1369641

Reputation: 49

int[] selectedRows = table.getSelectedRows();
List<Object> selectedObjects = new ArrayList<Object>();
for (int row : selectedRows) {
    selectedObjects.add(tableModel.getObject(row));
}
for (Object obj : selectedObjects) {
    tableModel.removeObject(obj);
}

// My TableModel is a subclass of this:

public abstract class ListTableModel<T> extends AbstractTableModel {

    private List<T> data;

    public void setData(List<T> data) {
        this.data = data;
    }

    public T getObject(int row) {
        return data.get(row);
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

}

Upvotes: 1

Sameera Perera
Sameera Perera

Reputation: 1

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel defaultModel = (DefaultTableModel) jTable1.getModel(); Vector newRow = new Vector(); defaultModel.removeRow(jTable1.getSelectedRow()); i = i - 1; }

Upvotes: -2

user4342758
user4342758

Reputation: 1

Try this:

int selectedIndex = table_.getSelectedRow();
while (selectedIndex >= 0) {
    int modelIndex = table_.convertRowIndexToModel(selectedIndex);
    tableModel_.removeRow(modelIndex);

    selectedIndex = table_.getSelectedRow();
}

Upvotes: 0

barwnikk
barwnikk

Reputation: 976

removeRows: {
    int[] lines = t.getSelectedRows();
    if(lines.length==0)
        break removeRows;
    for(int i=0; i<lines.length; i++) {
        lines[i]=t.convertRowIndexToModel(lines[i]);
    }
    Arrays.sort(lines);
    for(int i=lines.length-1; i>=0; i--) {
        dtm.removeRow(lines[i]);    
    }
}

Working with sorting, moving columns, multiple selection, etc.

Upvotes: 3

user3277595
user3277595

Reputation: 1

Try this

    public void removeSelectedFromTable(JTable table) {

        DefaultTableModel model = (DefaultTableModel) table.getModel();
        int indexes[] = table.getSelectedRows(); 
        int res = 0;
        for(int i = 0; i < indexes.length; i++) {
            res += (i>0)?(indexes[i]-indexes[i-1]-1):0;
            int index = table.convertRowIndexToModel(indexes[0]+res)
            model.removeRow(index);
        }
    }

Upvotes: 0

ajer
ajer

Reputation: 11

This code work for me!

DefaultTableModel model = (DefaultTableModel) Table.getModel();
    int nbrrow=Table.getRowCount();

        if(nbrrow>=1){
            int[] rows = Table.getSelectedRows();
            if(rows.length>=1){
            if(Table.getModel().isCellEditable(Table.getSelectedRow(),Table.getSelectedColumn())
                       &&Table.isEditing()==true)
               {
                   Table.getCellEditor().stopCellEditing();
                    for(int i=0;i<rows.length;i++){ 
                     model.removeRow(rows[i]-i);
                   }
               }else{
                            for(int i=0;i<rows.length;i++){ 
                             model.removeRow(rows[i]-i);
                           }

                }
            for(int i=0;i<Table.getRowCount();i++){
                           model.setValueAt(i, i, 0);
                       }
              Table.revalidate();
              Table.repaint();
            }
        }

Upvotes: 1

FRANCOIS Nicolas
FRANCOIS Nicolas

Reputation: 1

That solution works with header sorting and updates automatically the table (i.e.: it is not required to rebuid it).

The "Collecions.sort in reverse order" ennables to avoid IndexOutOfBondException.

private void deleteSelectedRows() {
        int[] selectedRows = table.getSelectedRows();
        table.clearSelection();

        // get model rows
        List<Integer> selectedModelRows = new LinkedList<Integer>();
        for (int i =`enter code here` 0; i < selectedRows.length; i++) {
            selectedModelRows.add(table.convertRowIndexToModel(selectedRows[i]));
        }

        Collections.sort(selectedModelRows, Collections.reverseOrder());

        for (int selectedModelRow : selectedModelRows) {
            tableModel.removeRow(selectedModelRow);
            tableModel.fireTableRowsDeleted(selectedModelRow, selectedModelRow);
        }
}

Upvotes: -2

christoffer
christoffer

Reputation: 81

This worked for me

int numRows = table.getSelectedRows().length;
for(int i=0; i<numRows ; i++ ) {

    m_tableModel.removeRow(table.getSelectedRow());
}

Upvotes: 8

filosofem
filosofem

Reputation: 111

int[] selectedRows = getTable().getSelectedRows();
        if (selectedRows.length > 0) {
            for (int i = selectedRows.length - 1; i >= 0; i--) {
                tableModel.removeRow(selectedRows[i]);
            }
        }

Upvotes: 11

DDSameera
DDSameera

Reputation: 9

I looked at all the solutions, but there are some exceptions, so I would like to add this answer.

for (int i = 0; i < raws.length; i++) {
    System.out.println("I : " + i);
    for (int j = 1; j <= 1; j++) {
        defaultTableModel.removeRow(0);
        jTStockJournal.clearSelection();
        defaultTableModel.fireTableDataChanged();
    }
}

Upvotes: -2

Alejandro
Alejandro

Reputation: 289

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

Upvotes: 25

Chantz
Chantz

Reputation: 5963

Why not just use this,

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


        for (int row : rows) {
            tm.removeRow(from.convertRowIndexToModel(row));
        }

        from.clearSelection();
}

Upvotes: 1

Related Questions