在退出Java程序之前,如何使JFrame上的Red [X]有n秒等待?

时间:2014-04-04 02:47:21

标签: java swing timer jframe windowlistener

我正在使用WindowListener,但无论如何窗口立即关闭。

代码:

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

1 个答案:

答案 0 :(得分:2)

  1. 确保setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)

  2. 使用javax.swing.Timer代替尝试并暂停线程。

  3. 这是一个例子。我将DELAY设置为3秒,但您可以将其更改

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