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:
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.
December 17th, 2007 at 8:10 am
Thank you very much for this! Setting this property really helped me in my project.
February 18th, 2008 at 4:48 pm
Thank you Nick!
This did the trick! Great!
July 11th, 2008 at 12:06 pm
Nice one Nick!
September 5th, 2008 at 7:57 pm
Just had to say Thanks!, I spent hours messing with focus lost stuff
October 31st, 2008 at 12:12 pm
excellent!
November 4th, 2008 at 10:31 am
Thanks a lot! Works just fine also for me! Was looking for code that stops editing when focus moves out of a JTable.
December 18th, 2008 at 2:52 pm
Thanks a lot!
January 15th, 2009 at 6:58 pm
!!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.
August 18th, 2009 at 6:46 pm
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.
February 4th, 2010 at 5:31 pm
man! you´re awesome!!! this code save me hours of work! Thanks a lot from Colombia!
August 19th, 2010 at 3:40 pm
Saved me a lot of work here as well!!!
Wonder why they don’t have it as a method in JTable…
September 9th, 2011 at 2:44 pm
Wow, that one is magic
I’ve been looking for a solution for hours, I didn’t expect it to be this simple
Big thanks!!