开发者

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.

  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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜