Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically deselecting and edited JTable cell

Tags:

edit

jtable

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

like image 352
John R Doner Avatar asked Jan 21 '23 04:01

John R Doner


2 Answers

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.

like image 106
Mark Avatar answered Jan 22 '23 20:01

Mark


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();

like image 39
Anatoly D. Avatar answered Jan 22 '23 19:01

Anatoly D.