Can anybody explain me this javax swing method?

Roman picture Roman · Jan 30, 2010 · Viewed 6.9k times · Source

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:

  1. Does "public void run" define a new method? If it is the case, why it is defined within another method (see "larger code" for reference)?
  2. If "public void run" defines a new methods, what is a reason to define a method containing only one line of code (createAndShowGUI)?
  3. What does "invokeLater" do? This is actually the most complicated question for me.

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!

Answer

danben picture danben · Jan 30, 2010

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. Runnables 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.