我正在使用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);
}
};
答案 0 :(得分:2)
确保setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)
使用javax.swing.Timer
代替尝试并暂停线程。
这是一个例子。我将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();
}
});
}
}