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
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With