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 ?
You can do it calling setRowSelectionInterval : table. setRowSelectionInterval(0, 0); to select the first row.
So you can call table. getSelectionModel(). isSelectionEmpty() to find out if any row is selected.
If using the DefaultTableModel , just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI. JTable table; … DefaultTableModel model = (DefaultTableModel) table.
If you have a JTable instance created, just use:
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With