John R Doner
John R Doner

Reputation: 2282

Programmatically deselecting and edited JTable cell

I have a JTable in which a user enters data in the cells. Then there is a "Save" button which collects the table data, formats it in csv, and saves it to a file.

However, if a user leaves the last cell edited in a selected state, and clicks the Save button, the data in that cell is taken as null, so the data for that cell is not saved to the file.

Since it is easy for a user to forget to deselect a cell (and why should they have to?), I need a method to programmatically deselect it. I tried the clearSelection() method for the table, to no effect.

Any suggestions?

Thanks in advance for any help.

John Doner

Upvotes: 4

Views: 3961

Answers (5)

Jeff Learman
Jeff Learman

Reputation: 3287

I had a similar problem and this fixed it, at table creation time:

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

Of course, this works only if whatever the user does causes the cell to lose focus, which was true in my case.

Upvotes: 0

Anatoly D.
Anatoly D.

Reputation: 317

There is a nice article about this: http://tips4java.wordpress.com/2008/12/12/table-stop-editing/ with some other way to work around

Quick summary: if (table.isEditing()) table.getCellEditor().stopCellEditing();

Upvotes: 3

Deval Khandelwal
Deval Khandelwal

Reputation: 3548

This worked for me :

if (jTable3.getCellEditor() != null) {
            jTable3.getCellEditor().stopCellEditing();
}

It stops editing of the jtable rather than cancelling the editing and retains the last editted value.

Upvotes: 1

wbeerens
wbeerens

Reputation: 11

You can use the stopCellEditing function from the CellEditor

if(table.getCellEditor().stopCellEditing()){...}
if it succeeds, get the selected row from the TableModel. The change will be in there

stopCellEditing

Upvotes: 1

Mark
Mark

Reputation: 49

You basically want to programmatically remove the focus from the cell being edited. You can try the following:

        table.editCellAt(-1, -1);

That changes the cell being edited to (-1, -1) which does not exist. So by removing the focus from the current cell on button click its data gets persisted. I've noticed that cell (0, 0) gets selected, if this happens try the following line after the above line.

        table.getSelectionModel().clearSelection();

That should clear the selection from the table's selection model. Hope this helps.

Upvotes: 4

Related Questions