我有一个框架,并希望在用户关闭它时提示保存文档.但如果他们取消,框架不应该关闭.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
FileState查看文档是否脏.如果不是它什么也不做,并返回true.如果它是脏的,它会询问用户是否要保存(是/否/取消).如果用户此时取消,则应该中止windowClosing.
我在网上看到的所有建议都涉及显式退出windowClosing方法,从而覆盖了JFrame.setDefaultCloseOperation()的使用,并重复了JFrame.processWindowEvent()中的代码.
我实际上有一个肮脏的解决方案,但想看看是否有更干净的解决方案.
干杯