如何使JFrame上的红色[X]在退出Java程序之前等待n秒?
我正在使用如何使JFrame上的红色[X]在退出Java程序之前等待n秒?,java,swing,timer,jframe,windowlistener,Java,Swing,Timer,Jframe,Windowlistener,我正在使用WindowListener来执行此操作,但无论如何窗口都会立即关闭 代码: 确保setDefaultCloseOperation(关闭时不执行任何操作) 使用javax.swing.Timer而不是尝试休眠线程 这里有一个例子。我将延迟设置为3秒,但您可以更改它 import java.awt.event.*; import javax.swing.*; public class WindowClosing { private static final int DELAY
WindowListener
来执行此操作,但无论如何窗口都会立即关闭
代码:
setDefaultCloseOperation(关闭时不执行任何操作)
javax.swing.Timer
而不是尝试休眠线程延迟设置为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();
}
});
}
}
是的,我发现这比使用线程更有效。谢谢
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();
}
});
}
}