isGUIInitialized() is false, now what?
I been looking at some code and I find people doing
public static void main(String[] args) {
new ExampleCode();
}
ExampleCode () {
EventQueue.invokeLater(this);
}
public void run() {
if (EventQueueMonitor.isGUIInitialized()) {
guiI开发者_如何学Cnitialized();
} else {
EventQueueMonitor.addGUIInitializedListener(this);
}
}
Which makes sense, but now my question is how they keep the code running. To my understanding the code goes to main--->ExampleCode--->Run and then it stops because GUI was not initialized. Does any of the calls start the GUI else where? I use the same steps on my program, but my GUI is not initialized.
Two of my example codes:
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
The example you posted is using accessibility related features, hence it is possible that the initialization may take more time. The practice that we follow while using Swing is to avoid heavy initialization on event queue. What the original author's logic does is that he waits for swing jframe etc. to initialize completely, then he initialized his own components.
// 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(); }
The actual initialization logic is written in createGUI method, which will either be called by Swing or by your own logic. You program will not terminate, since Swing uses its own non-daemon thread (i.e. unless you call System.exit, your swing program will not terminate).
Here is a simple example based on examples from the Swing tutorial:
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();
}
});
}
}
精彩评论