Binding Scala Objects to Swing Components

If you do Swing application development, especially the enterprise application type you know lots of code that looks like this:

  1. public class Person {
  2.     private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
  3.  
  4.     public void setName(String aName){
  5.         String oldValue = name;
  6.         name = aName;
  7.         pcs.firePropertyChange("name", oldValue, aName);
  8.     }
  9.  
  10.     public String getName(){
  11.         return name;
  12.     }

Having properties like this you can bind them to Swing components using JGoodies Binding like this:

  1.       MyBean bean = new MyBean();
  2.       BeanAdapter adapter = new BeanAdapter(bean, true);
  3.       ValueModel stringModel = adapter.getValueModel("name");
  4.       JTextField field = BasicComponentFactory.createTextField(stringModel);

If you don’t know JGoodies Binding you should read this article about it asap.

If you do form based Swing applications this is the way to go: don’t write Listeners, bind components.

Yet I have a huge problem with this code. Actually multiple problems:

  • You have to repeat the name of the property in four places and you will end up in hell if you don’t do it in the correct way: In the name of the setter, in the name of the getter, in the first argument to firePropertyChange and in the call to the binding framework.
  • A trivial property takes 8 lines of code. Thats EIGHT lines of code. Or depending on your code quality probably about 1/100th to 1/10th of a bug, for a trivial property.
  • Apart from being to much code, it also has a high degree of duplication, because it is the same pattern over and over again. Yet their doesn’t seem to be a reasonable way to abstract over this kind of thing

If you are willing to switch to another language you actually can abstract over this quite nicely. This of course in no surprise, since it should be easy to write a language that offers support for this kind of property. But that is not what I’m talking about. I’m of course talking about a little Scala goodness. How about this for defining a class with a property:

  1. class Person extends PropertyOwner {
  2.     val name : Property[String] = "smith"
  3. }

Note that there is only one line defining the property (including setting it to an initial value). So how would binding it to a JTextField look like? Like this:

  1.     val p = new Person
  2.     val nameTextField = new JTextField()
  3.     Binder.bind(p.name, nameTextField)

Note that I don’t use the String “name” anywhere. Its all just normal, strongly typed values. If I use firstName instead of name by accident, the compiler will complain. The trick is obviously that I actually use objects of type Property, instead of fields, getters and setters. Yet using this thing looks (almost) perfect natural:

  1.     val p = new Person
  2.     p.name := "Alf"
  3.     println(p.name())

The code to achieve this is rather simple and short. The key is that a Property has a apply method returning its value and an := operator as replacement for a setter.

  1. class Property[T](var value : T) {
  2.     var listeners = List[T => Unit]()
  3.  
  4.     def apply() = value
  5.  
  6.     def :=(aValue : T) {
  7.         if (value != aValue) {
  8.             value = aValue
  9.             fireEvent
  10.         }
  11.     }
  12.  
  13.     def registerListener(l : T => Unit) {
  14.         listeners = l :: listeners
  15.     }
  16.  
  17.     private def fireEvent {
  18.         listeners.foreach(_(value))
  19.     }
  20. }
  21.  
  22. object Property {
  23.     implicit def apply[T](t : T)(implicit owner : PropertyOwner) : Property[T] =
  24.         new Property(t : T)
  25.  
  26.     implicit def toT[T](p : Property[T]) : T = p()
  27. }
  28.  
  29. trait PropertyOwner {
  30.     implicit val THE_OWNER = this
  31. }
  32.  
  33. object Binder {
  34.     def bind(p : Property[String], textField : JTextField) {
  35.         var locked = false
  36.  
  37.         initTextField
  38.         syncFromTextFieldToProperty
  39.         syncFromPropertyToTextField
  40.  
  41.         def initTextField = p() match {
  42.             case null => textField.setText("")
  43.             case _    => textField.setText(p().toString())
  44.         }
  45.  
  46.         def syncFromPropertyToTextField {
  47.             p.registerListener { value : String =>
  48.                 if (textField.getText != value)
  49.                     textField.setText(value)
  50.             }
  51.         }
  52.  
  53.         def syncFromTextFieldToProperty = textField.getDocument.addDocumentListener(new DocumentListener() {
  54.             def changedUpdate(e : DocumentEvent) = updateProperty
  55.             def insertUpdate(e : DocumentEvent) = updateProperty
  56.             def removeUpdate(e : DocumentEvent) = updateProperty
  57.         })
  58.  
  59.         def updateProperty = {
  60.             p := textField.getText
  61.         }
  62.     }
  63. }

This is currently just a little toy, call it proof of concept if you like. It only works with JTextFields, and the event notification might needs tweaking, since it provides just the new value of the property right now. There are many more ideas how to use this as a basis for building nice clean code with a Swing GUI. Watch this blog for more ideas and toys like this.

Share:
  • DZone
  • Digg
  • del.icio.us
  • Reddit
  • Facebook
  • Twitter