Search code examples
javaswingexitjoptionpane

How to launch a pop up when a user clicks close on a Java Swing application


I have a JFrame that currently has setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Is it possible for me to change this so that when the user clicks close I launch an "Are you sure?" JOptionPane style pop up?

How can I do this?


Solution

  • You need to add a WindowListener. Here's an example:

    public class Test {
    
        public static void main(String[] args) {
            final JFrame frame = new JFrame();
            JLabel label = new JLabel("Test");
            frame.getContentPane().add(label);
            frame.pack();
    
            frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    
            frame.addWindowListener(new WindowAdapter() {
    
                @Override
                public void windowClosing(WindowEvent ev) {
                    int result = JOptionPane.showConfirmDialog(frame, "Sure?");
    
                    if (result == JOptionPane.OK_OPTION) {
                        frame.dispose();
                    }
                }
            });
    
            frame.setVisible(true);
        }
    }