对大多数人来说,我似乎有相反的问题。我有以下非常标准的代码来查看用户是否想在关闭窗口之前进行一些保存:
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
最佳答案
我刚刚尝试了这个最小的测试用例:
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 调用的注释并点击关闭按钮,则窗口不会退出。取消注释并点击关闭按钮,窗口关闭。
我不得不猜测您设置“关闭”变量的逻辑有问题。尝试仔细检查。
关于Java - 如何防止 WindowClosing 实际关闭窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7613577/