哪有一个Swing的WindowListener否决闭幕的JFrame [英] How can a Swing WindowListener veto JFrame closing

查看:151
本文介绍了哪有一个Swing的WindowListener否决闭幕的JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个框架,并且希望当用户关闭它来保存文档提示。但是,如果他们取消,框架应该不会关闭。

I have a frame, and want to prompt when the user closes it to save the document. But if they cancel, the frame shouldn't close.

frame.addWindowListener(new SaveOnCloseWindowListener(fileState));
...
public class SaveOnCloseWindowListener extends WindowAdapter {
    private final FileState fileState;

    public SaveOnCloseWindowListener(FileState fileState) {
        this.fileState = fileState;
    }

    public void windowClosing(WindowEvent e) {
        if (!fileState.onQuit())
            cancelClose();  
    }
}

FileState着眼于文档是否脏了。如果不是它什么也不做,并返回true。如果脏了,它会询问用户是否希望保存(YES / NO / CANCEL)。如果用户取消在这一点上,应该中止的windowClosing

FileState looks at whether the document is dirty. If it isn't it does nothing and returns true. If it is dirty, it asks the user if he wants to save (YES/NO/CANCEL). If the user cancels at this point, it should abort the windowClosing.

我已经看到了网上所有的建议包括明确退出的windowClosing方法中,从而覆盖使用JFrame.setDefaultCloseOperation(),并在复制的JFrame.processWindowEvent code()。

All the suggestions I've seen on the net involve explicitly exiting in the windowClosing method, thus overriding the use of JFrame.setDefaultCloseOperation(), and duplicating the code in JFrame.processWindowEvent().

其实我有一个肮脏的解决方案,但想看看是否有任何清洁剂的。

I actually have a dirty solution, but would like to see if there are any cleaner ones.

干杯

推荐答案

正确的方法是将 JFrame.setDefaultCloseOperation DO_NOTHING_ON_CLOSE 创建窗口时。然后只需调用调用setVisible(假)的Dispose()当你的用户接受收盘时,或当无所事事接近是不能接受的。

The right way is set JFrame.setDefaultCloseOperation to DO_NOTHING_ON_CLOSE when the window is created. And then just calling setVisible(false) or dispose() when your user accepts the close, or doing nothing when the close isn't accepted.

的全部目的 JFrame.setDefaultCloseOperation 仅仅是prevent实施需要 WindowListeners 的最简单的动作。通过这些默认关闭操作所执行的操作非常简单。

The whole purpose of JFrame.setDefaultCloseOperation is only to prevent the need to implement WindowListeners for the most simple actions. The actions performed by these default close operations are very simple.

编辑:

我已经添加了我所描述的解决方案。这是假设你想要的框架中完全删除。

I've added the solution I'm describing. This assumes you want the frame to be fully deleted.

frame.setDefaultCloseOperation(setDefaultCloseOperation);
frame.addWindowListener(new SaveOnCloseWindowListener(fileState));
...

public class SaveOnCloseWindowListener extends WindowAdapter {
    private final FileState fileState;

    public SaveOnCloseWindowListener(FileState fileState) {
        this.fileState = fileState;
    }

    public void windowClosing(WindowEvent e) {
        if (fileState.onQuit())
            frame.dispose();
    }
}

这篇关于哪有一个Swing的WindowListener否决闭幕的JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆