Non-blocking modal Swing progress dialog

2019-02-06 01:26发布

问题:

A daft question, but I really cannot get this to work: I have some long-running process in a Swing application which may take several minutes. I want to display a progress dialog to the user while this process is ongoing. I also want to prevent the user from performing further actions, eg pressing a button while the process is going on.

If I do the process on the EDT, this obviously prevents the end-user from doing anything while the process is going on. But because the EDT is busy processing, it never gets around to rendering the dialog's content, so I just get the outline of the dialog.

But if I do the process in a worker thread, the end-user can click buttons and cause the EDT to manipulate state that the worker is also manipulating at the same time, with bad stuff as a consequence. If I make the dialog modal, that does not happen, but modal in Swing also implies blocking, so the moment I call setVisible(true), the thread blocks forever.

So my current "solution" is to use a worker thread, and then spawn off a separate thread whose only purpose is to absorb the blocking nature of setVisible. Surely there must be a better solution!

So how do I get a dialog that prevents the user from interacting with the rest of the system (modal) but does not block the thread that causes it to be visible?

回答1:

You should be using the GlassPane from preventing the user from interacting. The good thing is this is modal for the user and not your program so your thread won't get blocked.

The great news is that you can also use it for cool GUI effects like shading the GUI portion busy and the user can't interact with. You can also display a busy gif image in the GlassPane.

Links:-

  1. Official tutorial on GlassPane
  2. Some helpful tutorials
  3. Another tut
  4. Oreilly's Swing Hacks is excellent.


回答2:

You must be doing something wrong. Try the tutorial on How to Use Progress Bars. If you can understand how that code works, it should give you the direction for achieving the required feature.

Note that progress bars are usually modal.