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 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01