Reputation: 3
I want to keep all the selected rows in the jtable and delete the rest of them. I found many answers regarding how to delete the selected rows but how can I delete the non selected rows only. Please help
Upvotes: 0
Views: 419
Reputation: 324098
A couple of tips:
Don't worry about the array of selected rows. The indexes of the selected rows is automatically adjusted as your add/remove a row from the model. Just start deleting rows from the end checking the selected state of each row as you go.
Convert the view index to the model index in case the table is sorted or filtered.
Then the basic code is:
DefaultTableModel model = (DefaultTableModel)table.getModel();
for (int i = model.getRowCount() -1; i >=0; i--)
{
if (! table.isRowSelected(i))
model.removeRow( table.convertRowIndexToModel(i) );
}
Upvotes: 1
Reputation: 6435
I worked out a more convenient way which works perfectly fine with all possible cases.
@Override
public void actionPerformed(ActionEvent e) {
int[] lines = table.getSelectedRows();
for (int i = 0; i < lines.length; i++) {
lines[i] = table.convertRowIndexToModel(lines[i]);
}
List<Integer> l = new ArrayList<Integer>();
for (int i : lines) {
l.add(i);
}
for (int i = table.getRowCount() - 1; i >= 0; i--) {
if (!l.contains(i)) {
model.removeRow(i);
}
}
}
I think it could be slimmed down a bit or a bit code could be moved to an own method which makes it look cleaner, but its working
Upvotes: 0
Reputation: 151
I could not test it at all, but i hope it helps:
public void removeSelectedRows(JTable table){
DefaultTableModel model = (DefaultTableModel) this.table.getModel();
int[] rows = table.getSelectedRows();
int rowsCount = table.getRowCount();
int deletedRows = 0;
for(int i=rowsCount-1;i>-1;i--){
if(i!=rows[rowsCount-1-deletedRows]){ //Check non-selected rows
model.removeRow(i);
deletedRows++;
}
}
}
Maybe there is an easiest way but this should work fine.
Upvotes: 0