Search code examples
javaswingtimerjframewindowlistener

How do you make the Red[X] on a JFrame have n second wait before exiting a program in Java?


I am using the WindowListener to this but the window closes immediately anyway.

Code:

WindowAdapter close =  new WindowAdapter()
{
  public void windowClosing(WindowEvent e)
  {
            try
            {
              Thread.sleep(2000);
            }
            catch(InterruptedException ie3)
            {
              System.out.println("Sleep interrupted");
            }
            System.exit(0);      
  }
 };

Solution

    1. Make sure you setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)

    2. Use a javax.swing.Timer instead of trying and sleep the thread.

    Here's an example. I set the DELAY to 3 seconds, but you can change it

    import java.awt.event.*;
    import javax.swing.*;
    
    public class WindowClosing {
        private static final int DELAY = 3000;
    
        public WindowClosing() {
            Timer timer = new Timer(DELAY, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                    ;
                }
            });
            timer.setRepeats(false);
            JFrame frame = createFrame(timer);
            frame.setVisible(true);
    
        }
    
        private JFrame createFrame(final Timer timer) {
            final JFrame frame = new JFrame();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    timer.start();
                    JOptionPane.showMessageDialog(frame, "WindowClosing");
                }
            });
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.setSize(400, 400);
            frame.setLocationRelativeTo(null);
            return frame;
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new WindowClosing();
                }
            });
        }
    }