Search code examples
javaswingevent-dispatch-threadinvokelater

Using Event Queue to execute a simple method in main()


I am working on a Java application that was developed by some guy as part of a research project. Following is the main method:

 public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                // Change the name of the application on a mac
                System.setProperty("com.apple.mrj.application.apple.menu.about.name",
                        "XX");

                // Use the top of the screen for the menu on a mac
                if( System.getProperty( "mrj.version" ) != null ) {
                    System.setProperty( "apple.laf.useScreenMenuBar", "true" );
                }

                try {
                    // Use system look and feel
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

                } catch (Exception e) {
                    System.out.println("Cannot use system's look and feel; using Java's default instead");
                }

                // Create a new instance of XX
                XX.getInstance();
            }
        });

    }

Now, I do not understand why was an event queue used instead of just using

 public static void main(String[] args) {

        //the MAC stuff!!

        XX.getInstance();        //this line creates the UI and the event handlers
    }

Is there any significance of using the EventQueue?


Solution

  • The properties should be set on the Initial Thread, and the GUI should then be scheduled for construction on the event dispatch thread. Alternative approaches are shown here.

    public static void main(String[] args) {
        // Change the name of the application on a mac
        System.setProperty(
            "com.apple.mrj.application.apple.menu.about.name", "XX");
        // Use the top of the screen for the menu on a mac
        if (System.getProperty("mrj.version") != null) {
            System.setProperty("apple.laf.useScreenMenuBar", "true");
        }
    
        java.awt.EventQueue.invokeLater(new Runnable() {
    
            @Override
            public void run() {
                // Create a new instance of XX
                XX.getInstance();
            }
        });
    }