Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java event queue event dispatch flush/trap events

I have a design related question that I am trying to find an answer to.

Here is the scenario.

Suppose that you want to do something expensive (time-consuming) as a result of user input (e.g. loading huge amounts data from some database, reading large files). The strongly recommended way is to do the time-consuming work in a separate thread and never ever block the EDT, or else the GUI will become unresponsive.

There are scenarios however when you should not provide inputs to the GUI unless the background task is finished. In my specific case, only after the background work is finished, I can determine which GUI elements should be visible and enabled/disabled. Only those GUI elements which should be visible and enabled should respond to the user inputs otherwise the behavior may be unpredictable in my specific case.

This is what I am doing to handle such a scenario.

Step 1: Before I am about to start a time-consuming operation.

  1. Change the cursor to a busy cursor.
  2. Add mouse listeners to the glasspane of component's top-level frame.
  3. Make the glasspane visible so that it can receive mouse events. The glasspane doesn't do anything as a result of mouse inputs.

Step 2: Execute the time-consuming operation in a background thread. The background thread has a finally block that notifies the event thread when the job is finished (completed or aborted due to an error).

Step 3:

  1. Switch the mouse cursor back to normal.
  2. Remove listeners from the glass pane.
  3. Make the glasspane invisible, so that mouse events go to their intended recipients.

Is this the correct approach to handle such situations?

What do you guys recommend?

like image 654
Santosh Tiwari Avatar asked Jul 21 '26 15:07

Santosh Tiwari


1 Answers

SwingWorker can be used in this context. Related controls can be disabled when the background task is started and re-enabled in done(). In this related example, the run button is conditioned to toggle between "Run" and "Cancel".

Addendum: A back-port to Java 1.5 is available here.

like image 54
trashgod Avatar answered Jul 24 '26 05:07

trashgod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!