JTable - How to force user to select exactly one row
java, jtable, swing
Solution
Now, you could add `MouseListener`s, `SelectionListener`s, `KeyListener`s and key bindings to try and solve this is issue. Or, you could go to the heart of the problem.
The `ListSelectionModel` is responsible for managing the selection details.
You could simply supply your own `ListSelectionModel` for the row selection
public class ForcedListSelectionModel extends DefaultListSelectionModel {
public ForcedListSelectionModel () {
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
@Override
public void clearSelection() {
}
@Override
public void removeSelectionInterval(int index0, int index1) {
}
}
And simply set it to your table...
table.setSelectionModel(new ForcedListSelectionModel());
Problem
I have to implement a JTable in which exactly one row has to be selected (always). Empty selection is not allowed. I'm selecting the first row during initialization: ``` table.setRowSelectionInterval(0, 0); ``` additionally, I'm using ``` table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); ``` But user can still deselect one row using CLick + Ctrl. What is the easiest way ensure, that one (exaclty) row is always selected in the table ?