简体   繁体   English

当模态对话框变得可见时如何通知线程?

[英]How to notify threads when modal dialog becomes visible?

I am setting a modal dialog as visible in a SwingWorker thread using SwingUtilities.invokeLater. 我正在使用SwingUtilities.invokeLater在SwingWorker线程中设置一个模态对话框。 I want the SwingWorker thread to wait until the dialog becomes visible. 我希望SwingWorker线程等到对话框变得可见。 What is the best way to do this? 做这个的最好方式是什么? I have put the following code in my doInBackground() method in the SwingWorker object. 我已将以下代码放在SwingWorker对象的doInBackground()方法中。

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

And in the overridden setVisible() method in the MyDialog class: 在MyDialog类中重写的setVisible()方法中:

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. 但是,这似乎不起作用,因为存在计时问题 - 必须在super.setVisible()之前调用notifyAll(),因此SwingWorker线程可以处于等待状态。

I'm trying to figure out a nice way to do this but I'm getting pretty frustrated! 我正在试图找到一个很好的方法来做到这一点,但我变得非常沮丧!

  • use JOptionPane instead of plain JDialog 使用JOptionPane而不是普通的JDialog

  • JOptionPane block code execution untill some action realized JOptionPane块代码执行,直到实现一些动作

  • you can to add JComponents to JOptionPane same as for JDialog 你可以将JComponents添加到JOptionPane就像JDialog

Do not manipulate the dialog from the worker's doInBackground() method. 不要操作worker的doInBackground()方法中的对话框。 Instead publish() an appropriate result and make the dialog visible from process() . 而是publish()一个合适的结果,并使该对话框从process()可见。 You can also register a PropertyChangeListener that will be fired in response to setProgress() calls from doInBackground() . 您还可以注册一个PropertyChangeListener ,它将响应来自doInBackground() setProgress()调用而被触发。 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. 顺便说一句,我会重申@ kleopatra和@mKorbel的建议,以便更好地解释究竟想要实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM