简体   繁体   中英

JTable - prevent the user from de-selecting all elements in the table

I have a table with fixed content that I know will never be empty.

I would like to use it as a radio button (loosely speaking): I want always one and only one row selected at a time.

I know already that I can set the selection model to SINGLE_SELECTION but (rather unexpectedly) this seems not to prevent the user from deselecting all rows in the table.

Is there a simple way to prevent the user from deselecting all rows in the table?

I can only think of something like:

@Override
public void valueChanged(ListSelectionEvent listSelectionEvent) {
    if (!listSelectionEvent.getValueIsAdjusting() && table.getSelectedRow() == -1) {
        table.selectRow(0);
    }
}

but, frankly, it seems a bit too clumsy for such a simple task (and I need to remember the old selection to better implement the pattern)...

Is there a easier/more elegant way?

Thank you!

Override the 'changeSelection' method, to NOT deselect, if this is the last row being deselected, like this

public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
            {
                if(!(toggle && jt.getSelectedRowCount() == 1))
                {
                    super.changeSelection(rowIndex, columnIndex, toggle, extend);
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM