import javax.swing.*; import java.awt.event.*; class WindowHandler implements WindowListener { private JFrame frame; public WindowHandler(JFrame frame) { this.frame = frame; } // this is called when the user tries to close the window public void windowClosing(WindowEvent e) { int choice = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit?", "Really Quit?", JOptionPane.YES_NO_OPTION); if (choice == JOptionPane.YES_OPTION) { frame.dispose(); } } // we must override all of these methods to implement the interface, but don't care about them public void windowOpened(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} } public class ReallyQuit { public static void main(String[] args) { // create and set up the window. JFrame frame = new JFrame("Button Example!"); // make the program close when the window closes frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowHandler(frame)); // add a button object JButton button = new JButton("Push Me!"); frame.getContentPane().add(button); // display the window. frame.pack(); frame.setVisible(true); } }