5
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        Example ex = new Example();
        ex.setVisible(true);
    }
});

Here a block of code follows new Runnable(). How do I understand this code? I don't remember we can pass a code block directly to any object in java.

OneZero
  • 11,556
  • 15
  • 55
  • 92
  • That is actually creating a "in line" class. See this question --> [java inline class definition][1] [1]: http://stackoverflow.com/questions/8913406/java-inline-class-definition – BlakeP Apr 29 '13 at 19:28

5 Answers5

7

It is not a code block. It is an object.

When you say,

new Runnable()

you are creating an object that implements the Runnable interface, specifically the run() method.

As the method name suggests, invokeLater() will invoke the run() method of your runnable interface implementation object (or Runnable object) at some later point in time.

As another poster mentioned, this is an example of Anonymous Classes. It is really a convenience mechanism to quickly write code in a more concise fashion. If you don't like this, you can do it this way -

Create a new class that implements Runnable -

public class RunnableImplementation implements Runnable
 {
   public void run() 
    {
        Example ex = new Example();
        ex.setVisible(true);
    }
 }

Then, the code in your example becomes -

SwingUtilities.invokeLater(new RunnableImplementation()); 
CodeBlue
  • 14,631
  • 33
  • 94
  • 132
4

It's creating an instance of an anonymous inner class. Rather than deriving a named class from Runnable and creating an instance of it, you can do the whole thing inline.

See Anonymous Classes.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
1

You are not passing any code block, you are actually overriding the run method of the Runnable class

Extreme Coders
  • 3,441
  • 2
  • 39
  • 55
0

How do understand this code? This is such called swing event queue which helps to prevent concurrency problems. It invokes method run() on each Runnable object in this queue in sequential order.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
0

Your code

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    Example ex = new Example();
    ex.setVisible(true);
  }
});

is equivalent to

SwingUtilities.invokeLater(new MyRunnable() );

where MyRunnable is a class that implements the Runnable interface with the code you have and is created only for this purpose and cannot be used again.

Note MyRunnable is not the actual name, just made it up to show the point.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186