Invert selection in JTable

When I click the button, I want the selected rows to be inverted (no selected rows should be selected, and the selected rows should not be selected).

Is there a built-in method in JTable for this?

+3
source share
5 answers

JTable doesn't seem to have a built-in way to do this. So I implemented it with the following code. (Hope this is useful for those facing a similar problem.)

int[] selectedIndexs = jtable.getSelectedRows();
jtable.selectAll();

for (int i = 0; i < jtable.getRowCount(); i++) {
    for (int selectedIndex : selectedIndexs) {
        if (selectedIndex == i) {
            jtable.removeRowSelectionInterval(i, i);
            break;
        }
    }
}
+2
source

To simplify Sudar's solution:

int[] selectedIndices = table.getSelectedRows();
table.selectAll();
for (int prevSel : selectedIndices) {
    table.removeRowSelectionInterval(prevSel, prevSel);
}
+2
source

JTable

0
0

- , . , , , .

The fastest way for tables with over several hundred rows is

/**
 * Invert selection in a JTable.
 *
 * @param table
 */
public static void invertSelection(JTable table) {
    ListSelectionModel mdl = table.getSelectionModel();
    int[] selected = table.getSelectedRows();
    mdl.setValueIsAdjusting(true);
    mdl.setSelectionInterval(0, table.getRowCount() - 1);
    for (int i : selected) {
        mdl.removeSelectionInterval(i, i);
    }
    mdl.setValueIsAdjusting(false);
}
0
source

Source: https://habr.com/ru/post/1729210/


All Articles