简体   繁体   English

Java | 如何在“永久”循环运行时关闭JFrame?

[英]Java | How to close a JFrame while a “forever” loop is running?

I programmed myself a little helper-tool. 我为自己编程了一些辅助工具。 It got a little GUI with the buttons "Run" and "Stop". 它带有一个带有“运行”和“停止”按钮的小图形用户界面。 If I press "Run" the program executes a loop that continuously does something (http requests - every hour a few ones). 如果我按“运行”,程序将执行一个循环,该循环连续执行某项操作(http请求-每小时几个)。

But now I have the problem that, when I press "Run", the button stays pressed and the program/GUI waits for the process to end. 但是现在我有一个问题,当我按下“运行”时,按钮保持按下状态,程序/ GUI等待进程结束。 In this time I can't close the Window or press the "Stop"-button. 此时,我无法关闭窗口或按“停止”按钮。 And because the process is running forever, I am never able to end it - of course I can end the process in task-manager. 而且由于该过程永远运行,所以我永远无法结束它-当然,我可以在任务管理器中结束该过程。

Is there a way to bypass this problem? 有没有办法绕过这个问题?

I look forward for a helpful answer ;-) 我期待一个有用的答案;-)

Without code one can only speculate, but you are most likely running everything on the same thread, meaning that the method which handles the button press also launches these requests. 没有代码,只能推测,但是您很可能在同一线程上运行所有内容,这意味着处理按钮按下的方法也会启动这些请求。

The problem with this approach is that everything is done on the Event Dispatching Thread, which is the thread which handles events and other UI operations. 这种方法的问题在于,所有事情都在事件分发线程上完成,该线程是处理事件和其他UI操作的线程。 Any lengthy operations on this thread will make your UI non responsive. 在此线程上进行的任何冗长的操作都会使您的UI无响应。

To solve this problem, you will need to have your Run event handler launch threads which do all the work. 要解决此问题,您将需要让Run事件处理程序启动线程来完成所有工作。 This will leave the EDT free to handle user interactions. 这将使EDT可以自由处理用户交互。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM