javaswinguser-interfaceswingutilitiesjava-threads

What exactly does the call to the SwingUtilities.invokeLater() method into the main class that perform a Swing application?


I am pretty new in Swing and I have the following doubt about this main class that start a Swing application founded on an tutorial project:

package com.caveofprogramming.designpatterns.demo1;

import javax.swing.SwingUtilities;

import com.caveofprogramming.designpatterns.demo1.controller.Controller;
import com.caveofprogramming.designpatterns.demo1.model.Model;
import com.caveofprogramming.designpatterns.demo1.view.View;

public class Application {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                runApp();
            }

        });
    }

    public static void runApp() {
        Model model = new Model();
        View view = new View(model);

        Controller controller = new Controller(view, model);
    }

}

So this class contains the main() method that is the method performed when the application start.

It perform SwingUtilities.invokeLater() method that create a Runnable object that contains the run() method that itself perform the runApp() method that is the entrypoint of my Swing application.

My doubt are related about what exactly does the SwingUtilities.invokeLater() method. What exactly does? and what is the Runnable object that is created as parameter of the invokeLater() method? It seems to me that it is an object that automatically implement the Runnable interface but I am not sure about it and it is not clear for me why have I to do it.

Can you help me to understand how exactly works the architecture of this simple Swing application?


Solution

  • This is really two questions rolled into one.

    1. SwingUtilities.invokeLater() makes sure that whatever you want to do happens on the Event Dispatcher Thread. Since Swing is strictly single threaded, this is required for everything that interacts with Swing and doesn't already run in the EDT (e.g. is called as a result of an event handler) The main() method of your application is one such example, as it's invoked by the VM on startup in its own separate thread (called, unsurprisingly, the Main Thread).
    2. This is an anonymous inner class. It's a shortcut for creating a class that implements Runnable and creating an instance of that class straight away. (Note that it isn't completely equivalent with doing that, there are small but important details in which it is different.) SwingUtilities.invokeLater() will then put this Runnable object in the Swing event queue, which will be processed by the EDT (usually a couple of moments) later, calling the run() method you provided.