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!

[529 byte] By [Jensenryaa] at [2007-10-3 8:54:37]
# 1
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);now add you windowListener, with confirm message
Michael_Dunna at 2007-7-15 4:04:37 > top of Java-index,Desktop,Core GUI APIs...
# 2
> frame.setDefaultCloseOperation(JFrame.DO_NOTHING> _ON_CLOSE);> > now add you windowListener, with confirm messageWindowListener isn't called!
hiwaa at 2007-7-15 4:04:37 > top of Java-index,Desktop,Core GUI APIs...
# 3

> 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();

}

});

}

}

Michael_Dunna at 2007-7-15 4:04:37 > top of Java-index,Desktop,Core GUI APIs...
# 4
Thanks for your example code.It works on Java 6 beta.It was a minor typo on my part of the code!
hiwaa at 2007-7-15 4:04:38 > top of Java-index,Desktop,Core GUI APIs...
# 5
> It was a minor typo on my part of the code!"been there, done that" (and I still do it, way too often)
Michael_Dunna at 2007-7-15 4:04:38 > top of Java-index,Desktop,Core GUI APIs...