t0mm0d
t0mm0d

Reputation: 192

How to notify threads when modal dialog becomes visible?

I am setting a modal dialog as visible in a SwingWorker thread using SwingUtilities.invokeLater. I want the SwingWorker thread to wait until the dialog becomes visible. What is the best way to do this? I have put the following code in my doInBackground() method in the SwingWorker object.

synchronized (myDialog) {
    while (!myDialog.isVisible()) {
            myDialog.wait();
    }
}

And in the overridden setVisible() method in the MyDialog class:

public void setVisible(boolean enabled) {
    synchronized (this) {
        notifyAll();
    }

    super.setVisible(enabled);
}

However, this does not seem to work as there is a timing issue - notifyAll() must be called before super.setVisible() and as a result the SwingWorker thread can be left in a waiting state.

I'm trying to figure out a nice way to do this but I'm getting pretty frustrated!

Upvotes: 0

Views: 323

Answers (2)

trashgod
trashgod

Reputation: 205855

Do not manipulate the dialog from the worker's doInBackground() method. Instead publish() an appropriate result and make the dialog visible from process(). You can also register a PropertyChangeListener that will be fired in response to setProgress() calls from doInBackground(). This example illustrates both mechanisms.

As an aside, I would reiterate @kleopatra's and @mKorbel's suggestion to better explain what exactly you are trying to achieve.

Upvotes: 1

mKorbel
mKorbel

Reputation: 109823

  • use JOptionPane instead of plain JDialog

  • JOptionPane block code execution untill some action realized

  • you can to add JComponents to JOptionPane same as for JDialog

Upvotes: 1

Related Questions