我正在使用 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);
}
};
最佳答案
确保您
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)
使用
javax.swing.Timer
而不是尝试让线程 hibernate 。
这是一个例子。我将 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();
}
});
}
}
关于java - 如何让 JFrame 上的 Red[X] 在退出 Java 程序之前等待 n 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852591/