user2397927
user2397927

Reputation: 1

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.

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.

Is there any way around this?

Upvotes: 0

Views: 200

Answers (1)

camickr
camickr

Reputation: 324157

and runs some background process with javax.swing.Timer.

Background process should not be run with a Timer. Timer code executes on the EDT. So a long running task will prevent the GUI from repainting itself and responding to events.

Start a separate Thread to execute your background task.

The easiest way to do this is to use a SwingWorker.

Read the section from the Swing tutorial on Worker Thread and SwingWorker for more information and working examples.

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.

Upvotes: 1

Related Questions