java – 如何在EDT上运行JOptionPane?

我仍然遇到空白的JOptionPanes问题.基于SO和Java Docs的研究,这显然与不使用EDT有关.我的问题是EDT及其方法究竟如何适用于JOptionPane?例如,终端错误输出很明显,下面的JOptionPane不在EDT上运行.具体缺少什么,Runnable之类的东西怎么样?

import javax.swing.*;
public class PaneDemo
{
public static void main(String[] args)
{
    final String[] TEXT ={
            //message
            "Hello, World!",
            //title
            "Greeting"};//end TEXT
    showMyPane(TEXT);
}//end main
public static void showMyPane(final String[] TEXT)
{
    JOptionPane.showMessageDialog(null, TEXT[0], TEXT[1], 
        JOptionPane.INFORMATION_MESSAGE);
    if(!SwingUtilities.isEventDispatchThread())
    {
        System.err.println("Err: GUI failed to use EDT.");
    }//end if(!SwingUtilities.isEventDispatchThread())
}//end showMyPane
}//end class PaneDemo

答案建议添加invokeLater.然而,这似乎并没有在BlueJ中表现得很好.

isEventDispatchThread()仍然在终端中返回错误.这只是因为它现在在错误的位置?

最佳答案
您可以在Event Dispatch Thread上创建JOptionPane,如下所示:

  final String[] TEXT = {
        //message
        "Hello, World!",
        //title
        "Greeting"};//end TEXT

     ...

    /**
     * Create GUI and components on Event-Dispatch-Thread
     */
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
                JOptionPane.showMessageDialog(null, TEXT[0] 
                      + "\n is on EDT: " + SwingUtilities.isEventDispatchThread(), TEXT[1],
                        JOptionPane.INFORMATION_MESSAGE);
        }
    });

看看Lesson: Concurrency in Swing 它应该可以帮助你理解它的全部意义

更新:

根据评论你应该在showPane(…)方法的每个调用上在EDT上启动JOptionPane,如下所示:

   public static void showMyPane(final String[] TEXT) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(null, TEXT[0] 
                      + "\n is on EDT: " + SwingUtilities.isEventDispatchThread(), TEXT[1],
                        JOptionPane.INFORMATION_MESSAGE);
            }
        });
    }//end showMyPane

    public static void main(String[] args) {
        final String[] TEXT = {
            //message
            "Hello, World!",
            //title
            "Greeting"};//end TEXT
        showMyPane(TEXT);
    }

转载注明原文:java – 如何在EDT上运行JOptionPane? - 代码日志