Verify closing of a window
I am trying to make my program prompt the user for confirmation before the program closes.
I have an exit item on a JMenu, and I can confirm using that method, but what if the user hits the X button up in the upper left corner? How do I confirm that the user wants to close the program if they use that button?
I've toyed with using a WindowListener for a windowClosing event, and that displays the dialog button to approve, but I cant get it to not close if the user doesn't want to exit. Any ideas? Thanks!
> WindowListener isn't called!
works OK in 1.4.0_01
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Testing
{
public void buildGUI()
{
JFrame f = new JFrame();
f.setSize(100,100);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
int closeIt = JOptionPane.showConfirmDialog(null,"Close?");
if(closeIt == JOptionPane.YES_OPTION) System.exit(0);
}
});
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
});
}
}