I have trouble understanding this simple code:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
Can anybody please explain me how it works (in simple terms because I am a newbie)? This short code is a part of this larger code.
To be more specific, I have the following questions:
I would like to emphasize one more time that I am a newbie and usage of "special" and "technical" words will produce even more questions.
Thank you in advance, if you decide to help me!
The shortest answer I can give is:
Runnable
is an interface in Java representing a type that defines a run
method. Any class that implements this interface must provide an implementation for run
. Runnable
s represent tasks that are to be executed by other parts of your system. Thread
is a well-known Runnable
.
When you have code that looks like new InterfaceName() { //implementation }
, that is called an anonymous class. The point of an anonymous class is to make a one-off class implementing the interface type. This class has no name, and as such we can never refer to it again. It is only used here.
Without knowing much about Swing, it looks like SwingUtilities.invokeLater()
accepts a Runnable
and...well, I would guess it invokes it later (how much later is probably described in the JavaDocs). But, the reason you would define run
here as simply another method invocation is that some code inside SwingUtilities
is going to be calling the run
method on this Runnable
; indeed, all it can possibly know about any Runnable
is that it defines a method with signature public void run()
, because that is the only method defined in the Runnable
interface.
Well, I guess that wasn't too short after all.