Stephan Schwab

Software development and farm life

Most common mistake: start Swing applications off the right thread

leave a comment »

While reading Improve Application Performance With SwingWorker in Java SE 6 from the Sun Developer Network I found that I made the most common mistake in Swing programming myself as well.

All Java programs start with an initial thread out of the main() method. A lot of people – including myself – will create the application main window as a JFrame there in main() and show the UI. That’s wrong!

The correct way is to use the Event Dispatch Thread (EDT) for all user interface related stuff. So creating the application main window outside of the EDT is wrong, because it might lead to thread synchronization problems later. The right way to do it is to use the invokeLater() method from SwingUtilities:

public class MainFrame extends javax.swing.JFrame {
 
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        new MainFrame().setVisible(true);
      }
    });
  }
}

Doing so has another advantage. The call to invokeLater() returns immediately allowing your application to perform other initialization tasks without delay. If a wait is required, one can use invokeAndWait() instead.

Written by Stephan Schwab

January 24, 2007 at 6:04 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 138 other followers