How can I get a JTable's default JTextField editor to stop editing(cause a setValueAt(row, col)) when the JTable loses focus?

Jon Wingfield

This is related to a previous Swing FAQ question. Depending on how you want the UI to behave you can stop table edits before subsequent actions occur (eg button clicks) or when focus is lost by adding a FocusListener to the JTable and implementing the focusLost method. The problem with the latter method is that often you don't have a context from which to decide how to end the table edit. For example, should the same processing occur if the table loses focus due to either a Cancel button or an OK button being clicked on the Dialog/InternalFrame? Or do you want to accept/validate the value on OK but discard it on Cancel? The FocusEvent doesn't give you the information to make this distinction.
Here's a method I use :

private void closeCellEditors(boolean validate) {
    TableCellEditor tce = null;
    if (table.isEditing()) {
        tce = table.getCellEditor();
    if (tce!=null) {
        if (validate) {
        } else {

If the new value needs to be validated the stopCellEditing() is called, which in turn calls setValue(...) on the TableModel, otherwise the change is rejected.