简体   繁体   English

如何使KeyListener使用主线程而不是EDT?

[英]How to get KeyListener to use main thread and not EDT?

In my program, I have a method that is called when a key is pressed. 在我的程序中,有一个按下键时会调用的方法。 That method shouldn't return until some task is completed, so it blocks the thread with something like: 在完成某些任务之前,该方法不应该返回,因此它会以类似以下方式阻止线程:

while (!taskIsDone);

and runs some background process with javax.swing.Timer . 并使用javax.swing.Timer运行一些后台进程。

However, since KeyListener is handled by the Event Dispatch Thread, the method blocks the Event Dispatch Thread, not the main Thread, and the program cannot run if the Event Dispatch Thread is being blocked. 但是,由于KeyListener是由事件调度线程处理的,所以该方法将阻塞事件调度线程,而不是主线程,并且如果事件调度线程被阻塞,则程序将无法运行。

Is there any way around this? 有没有办法解决?

and runs some background process with javax.swing.Timer. 并使用javax.swing.Timer运行一些后台进程。

Background process should not be run with a Timer. 后台进程不应与计时器一起运行。 Timer code executes on the EDT. 计时器代码在EDT上执行。 So a long running task will prevent the GUI from repainting itself and responding to events. 因此,长时间运行的任务将阻止GUI重新绘制自身并响应事件。

Start a separate Thread to execute your background task. 启动一个单独的线程来执行您的后台任务。

The easiest way to do this is to use a SwingWorker . 最简单的方法是使用SwingWorker

Read the section from the Swing tutorial on Worker Thread and SwingWorker for more information and working examples. 阅读Swing教程中有关Worker Thread和SwingWorker的部分,以获取更多信息和工作示例。

If you want to block further input while the task is executing, maybe you can display a progress bar so the user knows processing is happening in the background. 如果要在执行任务时阻止其他输入,则可以显示进度条,以便用户知道后台正在进行处理。

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

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