本文介绍了Swing模态对话框拒绝关闭 - 有时!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

// This is supposed to show a modal dialog and then hide it again. In practice,
// this works about 75% of the time, and the other 25% of the time, the dialog
// stays visible.
// This is on Ubuntu 10.10, running:
// OpenJDK Runtime Environment (IcedTea6 1.9) (6b20-1.9-0ubuntu1)

// This always prints
// setVisible(true) about to happen
// setVisible(false) about to happen
// setVisible(false) has just happened
// even when the dialog stays visible.

package modalproblemdemo;

import java.awt.Frame;
import javax.swing.JDialog;
import javax.swing.SwingUtilities;

public class Main {
    public static void main(String[] args) {
        final Dialogs d = new Dialogs();
        new Thread() {
            @Override
            public void run() {
                d.show();
                d.hide();
            }
        }.start();
    }

    static class Dialogs {
        final JDialog dialog;

        public Dialogs() {
            dialog = new JDialog((Frame) null, "Hello World", /*modal*/ true);
            dialog.setSize(400, 200);
        }

        public void show() {
            SwingUtilities.invokeLater(new Runnable() { public void run() {
                dialog.setLocationRelativeTo(null);
                System.out.println("setVisible(true) about to happen");
                dialog.setVisible(true);
            }});
        }

        public void hide() {
            SwingUtilities.invokeLater(new Runnable() { public void run() {
                System.out.println("setVisible(false) about to happen");
                dialog.setVisible(false);
                System.out.println("setVisible(false) has just happened");
            }});
        }
    }
}


推荐答案

事实证明,当你显示()/ setVisible(true)模态对话框时会发生的事情是在show / setVisible调用中运行第二个事件调度循环。一旦你了解它,这就很有意义。考虑到这一点,我最终得到了这段代码:

So it turns out that what happens when you show()/setVisible(true) a modal dialog is that a second event dispatch loop is run within the call to show/setVisible. Which makes perfect sense once you know about it. With that in mind, I ended up with this code:

public void runBlockingTask(final String taskName, final BlockingTask bt) {
    SwingUtilities.invokeLater(new Runnable() { public void run() {
        new Thread("Worker Thread: " + taskName) {
            @Override
            public void run() {
                bt.run();
                progressDialog.setVisible(false);
            }
        }.start();
    }});
    // NB This causes the event dispatch loop to be run inside this call,
    // which is why we need  to put everything after setVisible into an
    // invokeLater.
    progressDialog.setVisible(true);
}

这篇关于Swing模态对话框拒绝关闭 - 有时!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 09:19