Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable - How to force user to select exactly one row

Tags:

java

swing

jtable

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 ?

like image 908
guitar_freak Avatar asked Aug 19 '13 08:08

guitar_freak


People also ask

How do I select a row in a table Swing?

You can do it calling setRowSelectionInterval : table. setRowSelectionInterval(0, 0); to select the first row.

How can I tell if a row is selected in JTable?

So you can call table. getSelectionModel(). isSelectionEmpty() to find out if any row is selected.

How do you clear a JTable row?

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.


2 Answers

If you have a JTable instance created, just use:

jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
like image 98
Daniel Villanueva Avatar answered Oct 03 '22 22:10

Daniel Villanueva


Now, you could add MouseListeners, SelectionListeners, KeyListeners 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());
like image 33
MadProgrammer Avatar answered Oct 04 '22 00:10

MadProgrammer