Java - 如何防止WindowClosing实际关闭窗口 [英] Java - how do I prevent WindowClosing from actually closing the window

查看:934
本文介绍了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实际关闭窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆