javajtabletablecelleditor

Why is cancelCellEditing() not called when pressing escape while editing a JTable cell?


I have an editable JTable and have set a DefaultCellEditor like so:

    colModel.getColumn( 1 ).setCellEditor( new DefaultCellEditor( txtEditBox ) {
        // ...
        @Override
        public void cancelCellEditing() {
            super.cancelCellEditing();
            // handling the event
        }
        // ...
    }

However, when pressing escape while editing a cell in this column, though the editing mode is finished, this method is not called. Any ideas why? Am I doing something wrong? Is there a way to handle this (other than manually adding a KeyListener that is)?


Solution

  • The official way: You can register a CellEditorListener: AbstractCellEditor.addCellEditorListener(...). If the editing is canceled, editingCanceled(ChangeEvent e) should be called. Due to a SUN bug https://bugs.java.com/bugdatabase/view_bug?bug_id=6788481, editingCanceled is not called :(

    As workaround you can register your own action for the ESCAPE key and handle it yourself. But it will not work for resize events.

    Another solution (quick and dirty;-)): Overwrite the methode JTable.removeEditor() and insert your code after the super call.