问题描述
程序启动时,将创建一个新的JFrame.用户单击开始"按钮后,便创建并启动了一个线程.该线程执行的一部分是验证表单上的数据,然后使用该数据执行.验证数据后,线程将在原始帧上调用dispose(),然后创建一个新的JFrame作为控制面板.
When the program starts, a new JFrame is created. Once the user clicks the start button a thread is created and started. Part of this threads execution is to validate the data on the form and then execute with that data. Once the data has been validated the thread calls dispose() on the original frame and then creates a new JFrame that acts as a control panel.
该程序还有一种自动模式,它根本不显示任何GUI,该模式从配置文件读取数据,然后启动执行线程并运行所有内容,但没有控制面板.
There is also an automatic mode of the program that doesn't display any GUI at all, this mode reads data from a configuration file and then starts the execution thread and runs everything but without the control panel.
我希望程序在线程完成后结束,但是在GUI模式下,仅当用户也关闭控制面板时才结束.是否可以让线程等待框架关闭.我假设框架是从它自己的线程运行的?还是不是这样.
I want the program to end once the thread completes, but in GUI mode, only if the user has closed the control panel as well.Is it possible to make the thread wait for the frame to close. I assuming that the frame is run from it's own Thread? or is that not the case.
谢谢.
推荐答案
您选择的答案有点尴尬.使用Thread.sleep(1000)将每秒检查一次窗口状态.这不是性能问题,而只是不良的编码风格.而且您可能会有一秒钟的响应时间.
The answer you chose is a little awkward. Using Thread.sleep(1000) will check for window state every second. It is not a performance issue, but just bad coding style. And you may have a one second response time.
这段代码要好一些.
private static Object lock = new Object();
private static JFrame frame = new JFrame();
/**
* @param args
*/
public static void main(String[] args) {
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setVisible(true);
Thread t = new Thread() {
public void run() {
synchronized(lock) {
while (frame.isVisible())
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Working now");
}
}
};
t.start();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
synchronized (lock) {
frame.setVisible(false);
lock.notify();
}
}
});
t.join();
}
这篇关于如何使线程等待Java中的JFrame关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!