如何使用 DISPOSE_ON_CLOSE 或 EXIT_ON_CLOSE 的窗口关闭操作调用 ShutdownHook 线程 [英] How to invoke ShutdownHook thread with a window close operation of DISPOSE_ON_CLOSE or EXIT_ON_CLOSE
问题描述
假设 Runtime.getRuntime().addShutdownHook(new Thread()
已经正确设置,那么如何在 Java 应用程序窗口 (JFrame
) 时调用 ShutdownHook 线程>) 被关闭(在这种情况下是唯一的窗口)并且处理窗口默认关闭操作是 DISPOSE_ON_CLOSE
或 EXIT_ON_CLOSE
?
Assuming that Runtime.getRuntime().addShutdownHook(new Thread()
has been set up correctly, how can the ShutdownHook thread be invoked when a Java application window (JFrame
) is closed (in this case the only window) and the dispose window default close operation is DISPOSE_ON_CLOSE
or EXIT_ON_CLOSE
?
请注意,对于使用 System.exit(0)
处理的退出命令,然后通过 ShutdownHook 线程馈送,应用程序正确终止,因为所有关联的线程在 Java 应用程序退出之前终止.所以我想通过关闭 JFrame
窗口通过 ShutdownHook 线程清理来完成同样的事情.
Note that for a quit command handled with a System.exit(0)
which is then fed through the ShutdownHook thread, the application terminates correctly as all the associated threads are terminated before the Java application exits. So I want to accomplish the same thing by making the closing of the JFrame
window go through the ShutdownHook thread clean up.
推荐答案
这根据您的规范工作.如果我通过单击 X
按钮关闭框架,则会调用关闭挂钩.
This works according to your spec. If I close the frame by clicking the X
button, the shutdown hook is invoked.
import javax.swing.*;
class ShutDownHookDemo {
public static void endMessage() {
// clean up threads here..
System.out.println("Thanks for using the app.");
}
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
endMessage();
}
};
Runtime.getRuntime().addShutdownHook(t);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300,300);
f.setVisible(true);
}
}
这篇关于如何使用 DISPOSE_ON_CLOSE 或 EXIT_ON_CLOSE 的窗口关闭操作调用 ShutdownHook 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!