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 beco开发者_运维百科me 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.
- Change the cursor to a busy cursor.
- Add mouse listeners to the glasspane of component's top-level frame.
- 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:
- Switch the mouse cursor back to normal.
- Remove listeners from the glass pane.
- 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?
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.
精彩评论