Question

On clicking a button, I want the selected rows to be inverted (non-selected rows should be selected and selected rows should be non-selected).

Is there a build-in method in JTable to do it?

Was it helpful?

Solution

JTable doesn't seems to have a built-in way of doing this. So I implemented it with the following code. (Hope this is helpful for someone who is facing a similar issue.)

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

OTHER TIPS

To simplify Sudar's solution:

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

JTable does not have that feature

No, You will have to implement a cutsom ListSelectionListener

A refinement to above is to update selection using the selection model object, not the table object. When you update the selection via the table, each update fires a selection change event and it takes few seconds to update a table with just a few hundred rows.

The fastest way for tables with more than few hundred rows is this

/**
 * 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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top