开发者

Programmatically deselecting and edited JTable cell

开发者 https://www.devze.com 2023-02-19 07:19 出处:网络
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.

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


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消