isGUIInitialized()是假的,现在是什么?

时间:2011-09-23 16:29:15

标签: java swing user-interface awt

我一直在查看一些代码,我发现有人在做

 public static void main(String[] args) {
     new ExampleCode();
      }
 ExampleCode () {
      EventQueue.invokeLater(this);
    }

    public void run() {
        if (EventQueueMonitor.isGUIInitialized()) {
          guiInitialized();
        } else {
          EventQueueMonitor.addGUIInitializedListener(this);
        }
  }

这是有道理的,但现在我的问题是他们如何保持代码运行。根据我的理解,代码转到main ---> ExampleCode --->运行然后停止,因为GUI未初始化。是否有任何调用启动GUI其他位置?我在程序中使用相同的步骤,但我的GUI未初始化。

我的两个示例代码:

http://java.sun.com/javase/technologies/accessibility/docs/jaccess-1.1/examples/Explorer/Explorer.java

http://www.java2s.com/Code/Java/Swing-JFC/AGUItoshowaccessibleinformationcomingfromthecomponentsinan.htm

2 个答案:

答案 0 :(得分:2)

以下是基于Swing教程中的示例的简单示例:

import java.awt.*;
import javax.swing.*;

public class SSCCE extends JPanel
{
    public SSCCE()
    {
        add( new JLabel("Label") );
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("SSCCE");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new SSCCE() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

答案 1 :(得分:2)

您发布的示例使用与辅助功能相关的功能,因此初始化可能需要更长时间。我们在使用Swing时遵循的做法是避免在事件队列上进行大量初始化。原作者的逻辑所做的是他等待摆动jframe等完全初始化,然后他初始化了自己的组件。

// Check to see if the GUI subsystem is initialized correctly. (This is needed in JDK 1.2 and higher). If it isn't ready, then we have to wait. 

  if (EventQueueMonitor.isGUIInitialized()) { 
    createGUI(); 
  } else { 
    EventQueueMonitor.addGUIInitializedListener(this); 
  } 
} 

public void guiInitialized() { 
  createGUI(); 
}

实际的初始化逻辑是用createGUI方法编写的,它将由Swing或您自己的逻辑调用。你的程序不会终止,因为Swing使用自己的非守护程序线程(即除非你调用System.exit,否则你的swing程序不会终止)。