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

时间:2010-10-28 22:56:04

标签: java events user-interface

我想在关闭主应用程序窗口时显示“确认关闭”窗口,但不会让它消失。现在我正在使用windowsListener,更具体地说是windowsClosing事件,但在使用此事件时,主窗口已关闭,我想保持打开状态。

以下是我正在使用的代码:

注册听众

this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                thisWindowClosing(evt);
            }
        });

处理事件的实施:

private void thisWindowClosing(WindowEvent evt) {
    new closeWindow(this);
}

我也尝试在this.setVisible(true)方法中使用thisWindowClosing(),但它不起作用。

有什么建议吗?

1 个答案:

答案 0 :(得分: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);
            }
        });
    }
}