bitguru blog

a guru of bits, or just a bit player?

Swing single threading rule and JSR-296

Posted by bitguru on June 12, 2007

I didn’t make it to the JavaOne conference this year, but I notice that the slides and video (registration required) have been posted for the session on JSR-296: Swing Application Framework.

The Swing Application Framework has a number of goals, but one of them is to provide an Application class that has lifecycle methods for the programmer to implement, sort of like the existing Applet class. Application makes it easier not to violate the more-stringent Swing threading rule by invoking its startup method on the event thread. [I originally wrote by automatically invoking but it's not automatic. One must call launch(MyClass.class, argv) from main, which then calls startup(argv) via reflection.]

The idea is that JSR-296 will eventually be part of the JDK7 or JDK8. It’s possible to use it now as an external library, but the API is subject to change. It’s also possible to write code inspired by JSR-296 without actually using the library. Like other attempts to comply with the Swing threading rule, this is ugly but I throw it out there for discussion.

import javax.swing.*;

public class HelloWorld {

	/** If this class extended JSR-296's Application or
	 *  SingleFrameApplication class, this would be the
	 *  implementation of the abstract startup method. */
	protected void startup(String[] argv) {
		JLabel bulletin =
			new JLabel("Hello, world!", JLabel.CENTER);

		JFrame frame = new JFrame("Bulletin");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(bulletin); //add to CENTER
		frame.setSize(200, 150);
		frame.setVisible(true);
	}

	/** emulate JSR-296's launch(HelloWorld.class, argv) */
	public static void main(final String[] argv) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new HelloWorld().startup(argv);				
			}
		});
	}
}

I'm not real fond of this code. For starters, the protected and final keywords aren't beginner-friendly. (Though I suppose startup() could just as easily be declared public instead.) The search for beginner-friendly threading-compliant Swing code continues...

About these ads

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 )

Google+ photo

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

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: