JTable - How to force user to select exactly one row

I need to implement JTable in which I need to select only one row (always). Empty selection is not allowed. I select the first line during initialization:

table.setRowSelectionInterval(0, 0); 

In addition, I use

 table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 

But the user can still unselect one line with CLick + Ctrl.

What is the easiest way to ensure that a single row (exaccty) is always selected in a table?

+7
java swing jtable
source share
6 answers

You can now add MouseListener s, SelectionListener s, KeyListener and key bindings to try and solve this problem. Or you can go to the center of the problem.

ListSelectionModel is responsible for managing the details of the selection.

You can simply specify your own ListSelectionModel to select a row

 public class ForcedListSelectionModel extends DefaultListSelectionModel { public ForcedListSelectionModel () { setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } @Override public void clearSelection() { } @Override public void removeSelectionInterval(int index0, int index1) { } } 

And just set it to a table ...

 table.setSelectionModel(new ForcedListSelectionModel()); 
+14
source share

If you have a JTable instance, just use:

 jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
+18
source share

The easiest way to ensure that a single row (exaccty) is always selected in a table?

there are three (mostly) types of choices

 JTable.setRowSelectionAllowed(boolean); JTable.setColumnSelectionAllowed(boolean); JTable.setCellSelectionAllowed(boolean); 

change

works for me too

 int row = table.getSelectedRow(); if ((row > -1)) { table.setRowSelectionInterval(row, row); } } 
+4
source share

I would use JTable # setRowSelectionAllowed as it ensures that the row can be selected.

+1
source share

This code changes it back to the desired index and allows the user to never be updated.

 table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { table.setRowSelectionInterval(0,0); } ); 
0
source share

First do

 table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setRowSelectionInterval(0, 0); 

then set ListSelectionModel

0
source share

All Articles