Reputation: 147
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 when using this event the main window is closed and I want to keep it opened.
Here is 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?
Upvotes: 3
Views: 366
Reputation: 10136
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);
}
});
}
}
Upvotes: 3