Non-blocking modal Swing progress dialog
Asked Answered
A

2

16

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?

Achromat answered 7/10, 2010 at 22:16 Comment(1)
See also: #3954620Achromat
K
15

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.
Kriegspiel answered 11/10, 2010 at 6:59 Comment(0)
I
0

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.

Idellaidelle answered 8/10, 2010 at 8:35 Comment(3)
The code in the tutorial does not produce modal progress bars/dialogs. I can still manipulate the GUI while the process is running in the SwingWorker.Achromat
@Achromat I presume you refer to the ProgressMonitor demos. Try a JProgressBar in a modal dialog instead.Idellaidelle
Have done so. But if you run the demo, you can still manipulate the main window while the progress monitor is showing. If I make a replacement for progress monitor, it stops working, as the EDT is once again stuck waiting for setVisible to return.Achromat

© 2022 - 2024 — McMap. All rights reserved.