Java - 如何防止WindowClosing实际关闭窗口

时间:2011-09-30 16:52:55

标签: java swing jframe windowlistener

我似乎对大多数人都有相反的问题。我有以下非常标准的代码,看看用户是否想在关闭窗口之前进行一些保存:

  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

7 个答案:

答案 0 :(得分:65)

我刚试过这个最小的测试用例:

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调用进行了注释,并点击关闭按钮,则窗口不会退出。取消注释并按下关闭按钮,窗口关闭。

我必须猜测你的逻辑设置你的“关闭”变量是错误的。尝试仔细检查。

答案 1 :(得分:21)

这是关键,我认为:frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);在我编写的测试用例中有所不同。

答案 2 :(得分:7)

不确定你的问题在哪里,

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClosingFrame extends JFrame {

    private JMenuBar MenuBar = new JMenuBar();
    private JFrame frame = new JFrame();
    private static final long serialVersionUID = 1L;
    private JMenu File = new JMenu("File");
    private JMenuItem Exit = new JMenuItem("Exit");

    public ClosingFrame() {
        File.add(Exit);
        MenuBar.add(File);
        Exit.addActionListener(new ExitListener());
        WindowListener exitListener = new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                int confirm = JOptionPane.showOptionDialog(frame,
                        "Are You Sure to Close this Application?",
                        "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (confirm == JOptionPane.YES_OPTION) {
                    System.exit(1);
                }
            }
        };
        frame.addWindowListener(exitListener);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setJMenuBar(MenuBar);
        frame.setPreferredSize(new Dimension(400, 300));
        frame.setLocation(100, 100);
        frame.pack();
        frame.setVisible(true);
    }

    private class ExitListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            int confirm = JOptionPane.showOptionDialog(frame,
                    "Are You Sure to Close this Application?",
                    "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);
            if (confirm == JOptionPane.YES_OPTION) {
                System.exit(1);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ClosingFrame cf = new ClosingFrame();
            }
        });
    }
}

答案 3 :(得分:5)

对于这件事的处理做:
如果用户选择“是”,则在setDefaultCloseOperation(DISPOSE_ON_CLOSE);

的花括号内使用if else

如果选择取消,则使用setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

考虑例子:

int safe = JOptionPane.showConfirmDialog(null, "titleDetails!",  "title!!", JOptionPane.YES_NO_CANCEL_OPTION);

if(safe == JOptionPane.YES_OPTION){
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);//yes

} else if (safe == JOptionPane.CANCEL_OPTION) {
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//cancel
} else {
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);//no
}

答案 4 :(得分:1)

为了解决同样的问题,我尝试了本文的第一个答案。 作为单独的应用程序,它可以工作,但不是我的情况。 也许差异在于JFrame(在答案中)和FrameView(我的情况)。

public class MyApp extends SingleFrameApplication { // application class of my project
  ...
  protected static MyView mainForm; // main form of application
  ... 
}  
public class MyView extends FrameView {
    ...
    //Adding this listener solves the problem. 
    MyApp.getInstance().addExitListener(new ExitListener() {

      @Override
      public boolean canExit(EventObject event) {
        boolean res = false;
        int reply = JOptionPane.showConfirmDialog(null,
                "Are You sure?", "", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION) {
          res = true;
        }
        return res;
      }
      @Override
      public void willExit(EventObject event) {
      }
    });
    ...
}   

答案 5 :(得分:0)

不确定问题出在哪里,但这对我有用!

frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent evt) {
                            int res=JOptionPane.showConfirmDialog(null,
                                    "Do you want to exit.?");
                            if(res==JOptionPane.YES_OPTION){
                                    Cal.this.dispose();
                            }
            }                               
        });

答案 6 :(得分:0)

setDefaultCloseOperation()方法有助于解决问题。https://chortle.ccsu.edu/java5/Notes/chap56/ch56_9.html

查看此链接