Java 在JFrame close上终止正在运行的线程
当用户关闭Java 在JFrame close上终止正在运行的线程,java,multithreading,swing,jframe,windowlistener,Java,Multithreading,Swing,Jframe,Windowlistener,当用户关闭JFrame窗口时,如何调用额外的操作?我必须停止现有的线程 据我所知,setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)导致框架关闭并停止其线程。是否应在JFrame.EXIT\u ON\u CLOSE之后关闭线程 客户: static boolean TERMINATE = false; public static void main(String[] args) { // some threads created while(true)
JFrame
窗口时,如何调用额外的操作?我必须停止现有的线程
据我所知,setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)代码>导致框架关闭并停止其线程。是否应在JFrame.EXIT\u ON\u 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;
}
我需要关闭线程的插槽。这样做的最佳实践是什么?使用JFrame.EXIT\u ON\u CLOSE
实际上会终止JVM()。所有正在运行的线程将自动停止
如果要在JFrame
即将关闭时执行某些操作,请使用
- 您必须将
WindowListener
添加到JFrame
- 在
窗口关闭
方法中,您可以提供所需的代码
例如:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private JFrame frame = new JFrame();
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == 0) {
System.exit(1);
}
}
};
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == 0) {
System.exit(1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ClosingFrame cf = new ClosingFrame();
}
});
}
}
您可以在JFrame上设置默认关闭操作
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
另请参见。如果用户按下JFrame左上角的窗口关闭图标,则这是正确的,但如果JFrame通过调用其上的dispose()
关闭,则这不是正确的,而不是在非守护进程线程正在运行时。
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);