I need help understanding this java code

151 Views Asked by At

I'm following this Swing tutorial and I ran across this snippet of code:

    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            SimpleExample ex = new SimpleExample();
            ex.setVisible(true);
        }
    });

What's happening inside the EventQueue.invokeLater params?

2

There are 2 best solutions below

1
On BEST ANSWER

invokeLater expects an argument of type Runnable, i.e. an instance of a class implementing the Runnable interface. In this example, this method receives an instance of an anonymous class that implements Runnable.

Runnable only has a single method - run - so all the anonymous class instance has to implement is that run method.

In Java 8, there's an even shorter syntax, using a lambda expression :

EventQueue.invokeLater(
    () -> {
        SimpleExample ex = new SimpleExample();
        ex.setVisible(true);
    }
);
0
On

invokeLater()'s parameter has to be implementing Runnable, and in this case is an anonymous inner class - a class that has no name and (in this case) has only one object created, explicitly a new implementation of Runnable interface. This is mainly a Java hack used to allow referencing methods in legacy code. In new code, you can use lambdas and method references in most cases instead, e.g.

EventQueue.invokeLater( () -> {
        SimpleExample ex = new SimpleExample();
        ex.setVisible(true);
} );

This particular code you presented will just run the code in run() from EventQueue when it's time.