Java - how do I prevent WindowClosing from actually closing the window(Java - 如何防止 WindowClosing 实际关闭窗口)
问题描述
对大多数人来说,我似乎有相反的问题.我有以下非常标准的代码来查看用户是否想在关闭窗口之前进行一些保存:
I seem to have the reverse problem to most people. I have the following pretty standard code to see if the user wants to do some saves before closing the window:
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
boolean close = true;
// check some files, asking if the user wants to save
// YES and NO handle OK, but if the user hits Cancel on any file,
// I want to abort the close process
// So if any of them hit Cancel, I set "close" to false
if (close) {
frame.dispose();
System.exit(0);
}
}
});
无论我尝试什么,当我退出 windowClosing 时,窗口总是关闭.将 WindowAdapter 更改为 WindowListener 没有任何区别.奇怪的是,文档明确指出如果程序在处理此事件时没有明确隐藏或处置窗口,则窗口关闭操作将被取消",但它对我来说不起作用.还有其他方法可以处理框架上的 x 吗?TIA
No matter what I try, the window always closes when I come out of windowClosing. Changing WindowAdapter to WindowListener doesn't make any difference. What is weird is that the documentation explicitly says "If the program does not explicitly hide or dispose the window while processing this event, the window close operation will be cancelled," but it doesn't work that way for me. Is there some other way of handling the x on the frame? TIA
推荐答案
我刚刚尝试了这个最小的测试用例:
I've just tried this minimal test case:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
//frame.dispose();
}
});
frame.setVisible(true);
}
}
如果我保留 dispose 调用的注释并点击关闭按钮,则窗口不会退出.取消注释并点击关闭按钮,窗口关闭.
If I keep the dispose call commented, and hit the close button, the window doesn't exit. Uncomment that and hit the close button, window closes.
我不得不猜测你设置关闭"的逻辑有问题.多变的.尝试仔细检查.
I'd have to guess that something is wrong in your logic to set your "close" variable. Try double checking that.
这篇关于Java - 如何防止 WindowClosing 实际关闭窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java - 如何防止 WindowClosing 实际关闭窗口


- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01