我有一个框架,并希望在用户关闭它以保存文档时进行提示。但是如果它们取消了,框架就不应该关闭。
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。如果它是脏的,它会询问用户是否要保存(是/否/取消)。如果用户在这一点上取消,它应该中止windowClosing。
我在网上看到的所有建议都涉及在windowClosing方法中显式退出,从而覆盖JFrame.setDefaultCloseOperation()的使用,并复制JFrame.processWindowEvent()中的代码。
我实际上有一个很脏的解决方案,但我想看看是否有更干净的解决方案。
干杯
发布于 2010-09-23 19:20:10
正确的方法是在创建窗口时将JFrame.setDefaultCloseOperation设置为DO_NOTHING_ON_CLOSE。然后在用户接受close时调用setVisible(false)或dispose(),或者在close不被接受时什么也不做。
JFrame.setDefaultCloseOperation的整个目的只是为了避免需要为最简单的操作实现WindowListeners。这些默认关闭操作执行的操作非常简单。
编辑:
我已经添加了我所描述的解决方案。这假设您希望完全删除该帧。
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();
}
}发布于 2010-09-24 01:07:22
Closing an Application可能会让这个过程变得更容易一些。
发布于 2010-09-23 20:31:42
我认为这是Thirler答案的逻辑表达,也是我试图避免的。
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new SaveOnCloseWindowListener(fileState, JFrame.EXIT_ON_CLOSE));
public class SaveOnCloseWindowListener extends WindowAdapter {
private final int closeOperation;
private final Document document;
public SaveOnCloseWindowListener(int closeOperation, Document document) {
this.closeOperation = closeOperation;
this.document = document;
}
public void windowClosing(WindowEvent e) {
if (!document.onClose())
doClose((Window) e.getSource());
}
private void doClose(Window w) {
switch (closeOperation) {
case JFrame.HIDE_ON_CLOSE:
w.setVisible(false);
break;
case JFrame.DISPOSE_ON_CLOSE:
w.dispose();
break;
case JFrame.DO_NOTHING_ON_CLOSE:
default:
break;
case JFrame.EXIT_ON_CLOSE:
System.exit(0);
break;
}
}
}https://stackoverflow.com/questions/3777146
复制相似问题