I\'ve tried this:
public void removeSelectedFromTable(JTable from)
{
int[] rows = from.getSelectedRows();
TableModel tm= from.getModel();
while(
This worked for me
int numRows = table.getSelectedRows().length;
for(int i=0; i<numRows ; i++ ) {
m_tableModel.removeRow(table.getSelectedRow());
}
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();
}
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);
}
}
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);
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.
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);
}
}