How do I run JOptionPane on EDT?

风流意气都作罢 提交于 2019-12-01 07:18:18

问题


I'm still having problems with blank JOptionPanes. Based on research at SO and in Java Docs, this obviously has something to do with not using the EDT. My question is how exactly do the EDT and its methods apply to JOptionPane? For example, the terminal error output makes it quite clear that the JOptionPane below is not run on the EDT. What's missing specifically, and how does something like Runnable fit in?

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

An answer suggested adding invokeLater. That doesn't seem to render very well in BlueJ, however.

Also isEventDispatchThread() is still returning the error in the terminal. Is that simply because it is now in the wrong location?


回答1:


You can create JOptionPane on the Event Dispatch Thread like this:

  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);
        }
    });

Have a look at the Lesson: Concurrency in Swing it should help you understand what its all about

UPDATE:

as per comment you should initiate the JOptionPane on the EDT on each call in showPane(...) method like so:

   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);
    }


来源:https://stackoverflow.com/questions/13093499/how-do-i-run-joptionpane-on-edt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!