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.
Introduction: code block in Java A code block is a section of code enclosed in curly braces {} . Code blocks are used to group one or more statements. Code blocks can be nested, meaning you can have code blocks inside of other code blocks. The code block in the code above contains a single statement, int x = 10; .
Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. We can also create multiple objects and store information in it through reference variable.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With