Search code examples
javaswingjtabletablecelleditor

Is there an elegant way to make JTable stop editing when user closes the application window?


I am trying to find out an elegant way to make JTable stop cell editing (cancel it actually) when user closes the main application window. I know something like this can be done using the WindowAdapter but for this to work properly I need a reference to the window. Problem is I sometimes do not have it.


Solution

  • So far, this is the solution I am most satisfied with:

    All my JTable objects install themselves as HierarchyListener(s) with the following method to handle the HierarchyEvent:

    public void hierarchyChanged(HierarchyEvent e) {
        Window win = SwingUtilities.getWindowAncestor(this);
        if ((win != null) && (!win.equals(topLevelWindow))) {
            topLevelWindow = win;
            topLevelWindow.addWindowListener(new WindowAdapter() {
    
                @Override
                public void windowClosing(WindowEvent e) {
                    handleWindowClosing();
                }
    
            });
        }
    }
    
    private void handleWindowClosing() {
        if (table.isEditing()) {
            table.getCellEditor().cancelCellEditing();
        }
    }
    

    In the case of the project I work on, cancelling the editing when the application window closes is crucial because it sends the notification that the record is no longer in the editing state...

    Using hierarchy listener is also crucial because my JTable objects move from dockable to dockable (we use the excellent Docking Frames here) and can be in different windows at different times.