javaswingjxtable

Changing current selection in JXTable doesn't work?


I have a JXTable where the users need to introduce data, then save it. Only the thing is, the user has to deselect the last edited cell before saving it. If they don't, the data of that cell isn't saved.

The only thing I thought of is to change the current selection automatically just before saving. This is what i tried :

table.getSelectionModel().setSelectionInterval(0, 0);
table.getColumnModel().getSelectionModel().setSelectionInterval(0, 0);

OR

table.getSelectionModel().setLeadSelectionIndex(0);
table.getColumnModel().getSelectionModel().setLeadSelectionIndex(0);

None of both seem to work yet these are the only two methods I found to do this.

Can anyone please tell me how to do this properly or propose an alternative to also let it save the data from that last cell?


Solution

  • I am assuming the user clicks on another component (JButton) when he wishes to save data. If you have a reference to the JXTable when that event happens you could add the following piece of code there:

    if (table.isEditing()) {
        table.getCellEditor().stopCellEditing();
    }
    

    The stopCellEditing() should save the state of the model and allow you to save all the contents, including the currently selected / edited cell.


    EDIT: As kleopatra pointed out, the default (and better!) way to handle this is through the client property of JTable component:

    table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    

    For JXTable this should already be set though, which indicates that the way your UI handling of the save functionality works does not include moving the focus away from the table. So in essence you'd be better off changing the focus when your 'save' event is being fired.