tags:

views:

50

answers:

1

Hello,

I want to show a "Confirm Close" window when closing the main app window, but without making it disappear. Right now I am using a windowsListener, and more specifially the windowsClosing event. But, this when using this event, the main window is closed and I want to keep it opened.

He you have a chunk of the code I am using:

To register the listener

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

The implementation of the handling event:

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

Also I've tried using this.setVisible(true) in the thisWindowClosing() method but it doesn't work.

Any suggestions?

Thanks in advanced!

+3  A: 
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);
            }
        });
    }
}
Mike Clark
Thanks for the answer, but that doesn't work. The main window is closed once you click on Cancel.
testk
I don't know what to say. It works perfectly for me under Java 5 and Java 6. Make sure you paste and compile my example program exactly as it is, to prove that my code is working. Only then should you begin moving my approach over to your existing code. Did you remember to call frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); on your frame?
Mike Clark
Exactly...that was the problem. If I call "this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE" to my code. It works perfectly. That you so mach!
testk