当用户关闭应用程序窗口时,是否有一种优雅的方法可以使JTable停止编辑?

Dej*_*kic 2 java swing jtable tablecelleditor

我试图找到一种优雅的方法,当用户关闭主应用程序窗口时,使JTable停止单元格编辑(实际取消它).我知道可以使用WindowAdapter完成这样的事情,但为了使其正常工作,我需要对窗口的引用.问题是我有时候没有它.

tra*_*god 7

可能需要在多个级别处理突然退出.

  • 假设用户必须从表中导航以单击Exit控件,您应该通过设置表的"terminateEditOnFocusLost"属性来获得所需的结果.

    table.putClientProperty("terminateEditOnFocusLost", true);
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果你不得不求助于一个WindowListener或类似的,你可以停止如图所示明确编辑在这里.

    CellEditor cellEditor = table.getCellEditor();
    if (cellEditor != null) {
        if (cellEditor.getCellEditorValue() != null) {
            cellEditor.stopCellEditing();
        } else {
            cellEditor.cancelCellEditing();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 因为主机拥有该框架的装饰品,有些平台需要特殊处理拦截严密控制,为讨论在这里.

  • Preferences 尽最大努力坚持更新的价值观.


Dej*_*kic 4

到目前为止,这是我最满意的解决方案:

我的所有 JTable 对象都将自身安装为 HierarchyListener,并使用以下方法来处理 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

就我所从事的项目而言,应用程序窗口关闭时取消编辑至关重要,因为它会发送记录不再处于编辑状态的通知......

使用层次结构侦听器也至关重要,因为我的 JTable 对象从可停靠移动到可停靠(我们在这里使用出色的停靠框架),并且可以在不同时间位于不同窗口中。