Search code examples
javaswingjtablerowsdefaulttablemodel

How to keep selected rows and delete other from the jtable?


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


Solution

  • 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