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 实际关闭窗口
基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
