窗口关闭时的事件,但不关闭窗口。

3
我希望在关闭主应用程序窗口时显示一个“确认关闭”窗口,但不要让它消失。目前我正在使用一个windowsListener,更具体地说是windowsClosing事件,但是使用此事件时,主窗口被关闭,而我想保持它打开。
这是我正在使用的代码:
注册监听器:
this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                thisWindowClosing(evt);
            }
        });

事件处理的实现:
private void thisWindowClosing(WindowEvent evt) {
    new closeWindow(this);
}

我尝试在 thisWindowClosing() 方法中使用 this.setVisible(true),但它没有起作用。有什么建议吗?

你能发布一下你目前已经写好的代码吗? - EboMike
+1 对于一个我从未考虑过实现方式的常见情况。 - Pops
1个回答

3
package org.apache.people.mclark.examples;
import java.awt.event.*;
import javax.swing.*;

public class ClosingFrame extends JFrame {

    public ClosingFrame() {
        final JFrame frame = this;
        // Setting DO_NOTHING_ON_CLOSE is important, don't forget!
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                int response = JOptionPane.showConfirmDialog(frame,
                        "Really Exit?", "Confirm Exit",
                        JOptionPane.OK_CANCEL_OPTION);
                if (response == JOptionPane.OK_OPTION) {
                    frame.dispose(); // close the window
                } else {
                    // else let the window stay open
                }
            }
        });
        frame.setSize(320, 240);
        frame.setLocationRelativeTo(null);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClosingFrame().setVisible(true);
            }
        });
    }
}

谢谢您的回答,但那并不起作用。一旦您点击取消,主窗口就关闭了。 - testk
2
我不知道该说什么。在Java 5和Java 6下,它对我完美地运行。确保你粘贴并编译我的示例程序,以证明我的代码是可行的。只有这样,你才应该开始将我的方法移植到你现有的代码中。你是否记得在你的窗口上调用frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)? - Mike Clark
没错,那就是问题所在。如果我在代码中调用 "this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)",它就能完美地工作。非常感谢! - testk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接