Next page | Contents page |

Swing & threads - starting a GUI application

Events, Swing and threads

For efficiency, methods within the swing package are not synchronised, so they are not "thread safe".

In a Java application involving events the JVM always creates an event-dispatcher thread (EDT), in which event handling methods run, separate from the main thread.

Once a JFrame or other GUI component has been created, subsequent component changes should always be done in the event-dispatcher thread, to be safe.

In a Swing GUI program any time-consuming non-UI processing should be done in separate "worker" threads. In Java 6 new class javax.swing.SwingWorker facilitates this.

Starting a GUI app correctly

public class App extends javax.swing.JFrame
{
	public static void main (String [] a)
	{
		Runnable r = new Runnable ()
		{
			public void run ()
			{
				new App ().setVisible (true);
			}
		};

		java.awt.EventQueue.invokeLater (r);
		// Puts call to r.run () on end of EDT and returns
	} // main - Initial thread ends but EDT continues
} // App
Next page | Contents page |