A Java SwingUtilities invokeLater example

Java SwingUtilities FAQ: Can you demonstrate an example of the Java SwingUtilities invokeLater method?

I wanted to write a nice invokeLater example, but the code I have to share is a little too complicated. Fortunately I ran into the following example in the terrific book “Filthy Rich Clients” (see the link below), and it’s a good and simple example that I’d like to share it here with some added commentary.

A Java SwingUtilities ‘invokeLater’ example

Here’s the source code for their SwingUtilities invokeLater example:

public void actionPerformed(ActionEvent e)
{
  new Thread(new Runnable()
  {
    final String text = readHugeFile();
    SwingUtilities.invokeLater(new Runnable() 
    {
      public void run()
      {
        textArea.setText(text);
      }
    });
  }).start();
}

Discussion: Don’t block the GUI

Here’s a brief description of what they’re doing in this SwingUtilities code snippet.

First, they know they need to read a file which may potentially be very large, and they don’t want to block the UI, so this line of code is run in a Java Thread:

final String text = readHugeFile();

However, just doing that is not enough. When they place the contents of this file in their textArea, they want to make sure that happens on the Java EDT (the Event Dispatch Thread), and that’s where the SwingUtilities.invokeLater code comes in.

A big theme in proper Java Swing programming is “Don’t block the GUI,” and that's what this example demonstrates very well. They run their long-running task on a background thread, and then their Swing GUI is updated with this SwingUtilities.invokeLater code.

You can read more about the SwingUtilities.invokeLater method, but here are the best lines of information from that Javadoc:

Causes the Runnable to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.

As mentioned, I think this is a good example of the SwingUtilities invokeLater method, and I hope it’s helpful.

SwingUtilities invokeLater references

Here are a collection of links related to the SwingUtilities invokeLater topic:

You may also want to look into these other related classes:

Filthy Rich Clients book (Java client apps)

Before I go, here's a link to the terrific Filthy Rich Clients book on Amazon.