问题描述
当用户关闭 JFrame
窗口时,如何调用额外操作?我必须停止现有的线程。
How do I invoke extra operations when the user closes a JFrame
window? I have to stop existing threads.
据我所知, setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
导致框架被关闭,其线程被停止。是否应该在 JFrame.EXIT_ON_CLOSE
之后关闭线程?
As I understand it, setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
causes the frame to be closed and its thread to be stopped. Should threads be closed after JFrame.EXIT_ON_CLOSE
?
客户:
static boolean TERMINATE = false;
public static void main(String[] args) {
// some threads created
while(true) {
if(TERMINATE){
// do before frame closed
break;
}
}
}
private static JPanel startGUI(){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel gui = new JPanel();
f.add( gui);
f.setSize(500,500);
f.setVisible(true);
return gui;
}
我需要关闭套接字线程正在使用。这样做的最佳做法是什么?
I need to close sockets the thread's working with. What is the best practice to do that?
推荐答案
使用 JFrame.EXIT_ON_CLOSE
实际上终止了JVM()。所有正在运行的线程都将自动停止。
Using JFrame.EXIT_ON_CLOSE
actually terminates the JVM (System.exit
). All running threads will automatically be stopped.
如果要在 JFrame
即将关闭时执行某些操作,使用。
If you want to perform some action when a JFrame
is about to close, use a WindowListener
.
JFrame frame = ...
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// close sockets, etc
}
});
这篇关于在JFrame关闭时终止正在运行的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!