Making Swing Groovy, Part III: EDT

In this entry in my “Making Swing Groovy” series, I want to talk about threading issues. Specifically, how to work with the Event Dispatch Thread. As a step along the way, let me first respond to a comment made about my first post in this series.

Kirill Grouchnikov collects interesting Swing-related links every week. He was kind enough to link to my first post, and rightly pointed out that in my Java example, I’d make some errors. As he said,

“… the Swing example is not the best one, violating the EDT rules, working with the content pane and not centering the frame in the monitor, and the author admits some of these points.”

Let me say up front that I’m grateful for his comments. That’s how I learn. Part of the reason I post here (other than just the joy of sharing what I’ve learned) is to find out what I’ve been doing wrong, or, if I’m okay, what I can do better. One of the principles I live by is, “I’m often wrong, but I don’t stay wrong.” So keep those cards and letters coming. ūüôā

Here’s the code that Kirill addressed:

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

public class EchoGUI extends JFrame {
	private JTextField input = new JTextField(20);
	private JLabel prompt = new JLabel("Input text: ");
	private JLabel echo = new JLabel("Echo: ");
	private JLabel output = new JLabel();

	private Container cp = this.getContentPane();

	public EchoGUI() {
		super("Echo GUI");
		cp.setLayout(new GridLayout(0,2));  // 2 cols, as many rows as necessary

		cp.add(prompt);
		cp.add(input);
		cp.add(echo);
		cp.add(output);

		input.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				output.setText(input.getText());
			}
		});

		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setSize(300,100);
		setVisible(true);
	}

	public static void main(String[] args) {
		new EchoGUI();
	}
}

First, Kirill was right about my working with the content pane rather than adding my components directly to the JFrame instance. I remember way back in the Java 1.0 days (holy AWT, Batman), you added components directly to the instance of java.awt.Frame. Then, when Swing came along, you weren’t supposed to do that any more. Instead, you added to the content pane in front of the JFrame. That held true for Java 1.2, 1.3, and 1.4. Finally, in Java 1.5, you could go directly to the JFrame again, because now adding to the frame redirects to adding to the content pane. I need to retrain myself to do that.

Here is a link to a good post that explains why everything changed and then changed back.

Another of Kirill’s comments was that I didn’t center the frame on the monitor. I used to do that via code like

Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();

From that I can get the width and height of the screen, and then using the width and height of the frame I can center everything. I can do that, but here it seems a bit like overkill.

Finally, we come to the real issue, which is also the subject of this post. As he said, I violated the EDT rules, and that’s bad.

Arguably Rule #1 of Swing GUI’s is “Only update GUI Elements in the Event Dispatch Thread (EDT).” From what I gather from frequent posts about that issue across the web, this is an error as common to Swing developers as forgetting to close database connections is when writing JDBC code. And again, this is one of those situations in Swing where the rules have changed multiple times, although maybe it’s more accurate to say that the rule hasn’t changed, but the way to implement it has.

First, some quick background. Every Swing program involves multiple threads. First, there are the initializing threads, which start up the GUI. In a Java application, that’s the main method. Then there is the Event Dispatch Thread, which maintains an Event queue that handles all the GUI updates, and finally there are any background threads that are used to manage long-running processes. If you make sure that non-GUI processes are off the EDT, then the GUI will remain responsive while the application is doing other work.

As of JDK 1.6, the standard library now has the class javax.swing.SwingUtilities, which contains the methods invokeLater and invokeAndWait. According to the concurrency lesson in the Swing tutorial, the proper way to create a GUI is

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        void run() {
            \\  ... instantiate the GUI ...
        }
    );
}

The invokeLater method creates the Runnable object and gives it to the EDT to add to the event queue. The alternative method invokeAndWait does the same thing, but it blocks until the task is completed.

What does Groovy bring to this picture? As usual, Groovy simplifies matters. Groovy adds three helpful methods to groovy.swing.SwingBuilder: edt, doLater, and doOutside.

What do they do? One of the best things about using an open source API is that, well, you have access to the source code. For the edt method, the implementation looks like (paraphrased):

public SwingBuilder edt(Closure c) {
    if (SwingUtilities.isEventDispatchThread()) {
        c.call(this)
    } else {
        // ...
       SwingUtilities.invokeAndWait(c)
       // ...
    }
}

In other words, if we’re in the EDT already, invoke the closure. If not, call invokeAndWait to get to the EDT.

Likewise, for doLater:

public SwingBuilder doLater(Closure c) {
    // ...
   SwingUtilities.invokeLater(c)
   // ...
}

and for doOutside:

public SwingBuilder doOutside(Closure c) {
    // ...
   Thread.start(c)
    // ...
}

So what’s the bottom line?

  • edt: use the EDT through invokeAndWait
  • doLater: use the EDT through invokeLater
  • doOutside: create a worker thread and start it (off the EDT)

Incidentally, SwingBuilder also has a build method specifically designed to construct the GUI. How does it handle threading?

public static SwingBuilder build(Closure c) {
    SwingBuilder builder = new SwingBuilder()
    return builder.edt(c)
}

That’s the whole method — create the buillder and then build the GUI on the EDT, synchronously. That’s why all of our previous examples of SwingBuilder, which only used the build method on the builder, ran correctly. They’re doing the initial construction on the EDT, as they should.

Ultimately, practical examples of Groovy Swing code uses actions that take advantage of these methods, as in

swing.actions() {
    action(name:'myMethod') {

        doOutside {
            model.prop = textField.text
            // ... other model property updates ...
            def ok = someLongRunningService(model)

            doLater {
                model.ok = ok
}  }   }  }

And there you have it. Grab the data and update the model outside the EDT, then run the long running application. When it’s finished, update the GUI in the EDT. (Note that here we’re updating the model in the EDT because the model properties are bound to the GUI elements, so changes in model properties will result in a GUI update. See my previous post in this series for details.)

From here it’s only a short step to Griffon.

Making Swing Groovy, Part II: Binding

In my previous post in this series, I presented a trivial Echo GUI written in Groovy. ¬†By using SwingBuilder and closures, the code for the GUI was dramatically simplified compared to the Java version. ¬†But Groovy can go beyond that. ¬†In this post, I’ll talk about the bind method and the @Bindable annotation, which help transform Swing development into the MVC structure of Griffon.

The code for the Echo GUI currently consists of:

import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC

SwingBuilder.build() {
    frame(title:'Echo GUI', size:[300,100],
        visible:true, defaultCloseOperation:WC.EXIT_ON_CLOSE) {
        gridLayout(cols: 2, rows: 0)
        label 'Input text: '
        input = textField(columns:10, 
            actionPerformed: { output.text = input.text })
        label 'Echo: '
        output = label()
    }
}

The closure assigned to the actionPerformed property transfers the input from the text field to the output label.  In order to make that happen, both the field and the label were given names that could be referenced inside the closure.

Groovy 1.5+ includes a method called bind, which works with bound properties in the ancient JavaBeans specification. ¬†For those whose only exposure to JavaBeans is through POJO’s on the server side, the original JavaBeans framework was designed to support GUI builders. ¬†It looked and felt much like building GUIs in VB, in that you dragged these “beans” onto a palette, hooked them together, and set the values of their properties. ¬†It was a way of writing Java user interfaces without writing any Java code, at least until you wanted the various widgets to actually do something.

I remember back around 1998, I convinced my boss at the time to purchase Sun’s proposed IDE based on beans. ¬†I think it was called Sun Java WorkBench, or something like that. ¬†It cost about $99, and it came with beans that you could drag and drop, and you could add your own jar files full of beans as well. ¬†While it looked pretty cool, you didn’t have the source code for any of the beans, which limited their usefulness.

Java on the client side didn’t really take off, and the market for the IDE certainly didn’t pan out. ¬†I do remember that the JavaBeans specification — written largely to support the client-side development model — brought us many aspects of Java that we take for granted now. ¬†My first encounter with serialization came from there, as well as reflection, though they used the extremely awkward name introspection for it. ¬†In addition to implementing java.io.Serializable, JavaBeans according to the spec were also supposed to have default constructors and the now-infamous naming convention for getters and setters for all the properties. ¬†Actually, providing a getter method was sufficient to define a property of a JavaBean.

The spec also referred to various types of properties, like bound and constrained, and JavaBeans were also supposed to implement the PropertyChangeListener interface.

Very few Java programs were actually written using those JavaBeans, and the expected third-party market in JavaBeans libraries never seemed to develop. ¬†I seem to recall that there were a couple of success stories (wasn’t IBM’s VisualAge for Java supposed to be written using the original JavaBeans spec?), but mostly the whole technology went away.

It wasn’t until a few years later that JavaBeans re-emerged, as the way to get Java code out of JavaServer Pages. ¬†Sun’s Model 1 architecture consisted entirely of JSPs and JavaBeans, with no explicit servlets anywhere. ¬†Model 2 changed all that by using servlets for controllers, but that came later. ¬†By then, though, people used what we now call POJO’s for model classes, and you were still supposed to make your beans serializable, but all that stuff about property change listeners was largely ignored.

Groovy gives us a chance to use JavaBeans as model classes in an especially easy way. ¬†First, here’s an illustration of a simple GUI that uses the bind method in Groovy.

import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC
import java.awt.BorderLayout as BL

SwingBuilder.build() {
    frame(title:'Binding to Slider', pack:true, visible:true, 
        defaultCloseOperation:WC.EXIT_ON_CLOSE) {
        panel(constraints:BL.CENTER) {
          slider(id:'sl')
        }
        panel(constraints:BL.SOUTH) {
          label 'Slider value: '
          label(text:bind(source:sl, sourceProperty:'value'))
        }
    }
}

Here we’re taking advantage of the fact that all Swing widgets extend Component, which means they support property change listeners. ¬†In this case, we have a slider with a property called value. ¬†The bind method assigns the text of the label to the value property of the slider. ¬†Dragging the slider immediately updates the label.

This is seriously cool, and means that the Echo GUI shown above can be made even more responsive by replacing the actionListener by binding the output label directly to the input text field.

import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC

SwingBuilder.build {
    frame(title: 'Regular Binding (Groovy)', size: [300,100], 
        visible:true, defaultCloseOperation: WC.EXIT_ON_CLOSE ) {
        gridLayout(cols: 2, rows: 0)
        label 'Input text: '
        textField(columns:10, id:'tf')
        label 'Echo: '
        label(text:bind(source:tf, sourceProperty:'text'))
    } 
}

The result is that now, any characters typed into the text field are immediately transferred into the label. Deletes work the same way. The text in the output label is bound to the value of the input text field.

While this is interesting and even useful, a true model-view-controller architecture wouldn’t always bind widgets to other widgets. Instead, input values would be transfered to a model class, and then the model values would be sent to the output view. What we need, therefore, is a way to bind the view elements to an actual Java bean.

If this was Java, we would introduce a class that supported property change capabilities. Consider such a model class in Java:

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class Message {
    private String text;
    private PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    public String getText() { 
        return text; 
    }

    public void setText(String text) { 
        pcs.firePropertyChange("text", this.text, this.text = text); 
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(listener);
    }
	
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(listener);
    }
}

The Message class has a single property, called text. It also relies on the PropertyChangeSupport class to enable it to add and remove property change listeners. When the text property is changed, the setText method fires a property change event to all the listeners, where the arguments to the firePropertyChange method are the name of the property, its old value, and the new value.

How does Groovy simplify this? The key is the @Bindable annotation, which is currently only in Groovy 1.6 beta 2. Fortunately, that version is included in Griffon, though I did go to the trouble to download and rebuild it myself (a post for another time).

Using Groovy 1.6b2, here’s the equivalent Groovy bean:

import groovy.beans.Bindable

class Message {
    @Bindable def text
}

Seems almost unfair, doesn’t it? Add an annotation to the field, and you’re done. It’s hard to get much simpler than that.

Now all you need is a listener. In Java land, the GUI would use something like:

//...
    private Message msg = new Message();
//...
    msg.addPropertyChangeListener(new PropertyChangeListener(){
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            output.setText((String) evt.getNewValue());
        }
    });
//...

again using an anonymous inner class to respond to the change. By contrast, here is the Groovy version (where in this case the code is sufficiently succinct that I can include the whole thing):

import groovy.swing.SwingBuilder
import javax.swing.WindowConstants as WC

def model = new Message()

SwingBuilder.build() {
    frame(title:'Echo GUI', size:[300,100],  
        visible: true, defaultCloseOperation:WC.EXIT_ON_CLOSE) {
        gridLayout(cols: 2, rows: 0)
        label 'Input text: '
        input = textField(columns:10, 
            actionPerformed: { model.text = input.text })
        label 'Echo: '
        label(text: bind { model.text })
    }
}

Once again, this won’t work unless you’re using Groovy 1.6b2 or above. The bind method has been modified to take a closure as its last argument, and the closure in question refers to the text property of the model, rather than to another widget. Note that now I’ve gone back to implementing actionListener, because I have to get the text value from the view into the model, so it’s not quite as clean as before. That could be changed, but at the moment it seems reasonable to do it that way.

Of course, if we have a model and we have a view, what we need next is a controller. Griffon shows how to do that, but I’ll leave it for another post.

The bottom line is that by using Groovy’s bind method and @Bindable annotation, constructing a GUI based on a realistic MVC architecture is now viable, and even easy.

%d bloggers like this: