JTable editor – commit change on loss of focus

There is a known issue with JTables whereby the changes made in a cell editor are not committed when focus is lost.

This can result in the table staying in ‘edit mode’ with the stale value in the cell being edited still showing, although the change has not actually been committed to the model.

- this has bug id 4709394
Link to Bug Report

In fact what should happen is for this method on CellEditor to be called when focus is lost:

     /**
     * Tells the editor to stop editing and accept any partially edited
     * value as the value of the editor.  The editor returns false if
     * editing was not stopped; this is useful for editors that validate
     * and can not accept invalid entries.
     *
     * @return  true if editing was stopped; false otherwise
     */

    public boolean stopCellEditing();

So the editor can choose whether to accept the new value and stop editing, or have the editing cancelled without committing.

There is a magic property which you have to set on the JTable instance to turn this feature on:

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

Setting this hidden property should make the whole thing work as expected.




You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

12 Responses to “JTable editor – commit change on loss of focus”

  1. Thank you very much for this! Setting this property really helped me in my project.

  2. Sergey Bondarenko Says:

    Thank you Nick!
    This did the trick! Great!

  3. Nice one Nick!

  4. Just had to say Thanks!, I spent hours messing with focus lost stuff

  5. excellent!

  6. Thanks a lot! Works just fine also for me! Was looking for code that stops editing when focus moves out of a JTable.

  7. Thanks a lot!

  8. !!Warning!!
    This is a great fix if you only need your table to render Swing’s standard components. I’m using a custom component in one of my table columns and this code doesn’t allow me to access it. It thinks that I’m switching focus to an exterior component and fires stopEditing when I try to change the value in that particular column.

  9. This one line of code saved me HOURS of work. I’ve been writing Swing for a couple of years, and never saw anything like this. Thank you, sir.

  10. man! you´re awesome!!! this code save me hours of work! Thanks a lot from Colombia!

  11. Saved me a lot of work here as well!!!
    Wonder why they don’t have it as a method in JTable…

  12. Wow, that one is magic :D

    I’ve been looking for a solution for hours, I didn’t expect it to be this simple :)

    Big thanks!!

Leave a Reply