Wednesday, November 4, 2009

Another Reason to look at Scala for GUI

It's just a simple thing - a form GUI to edit domain objects stored in XML. We even have a schema to describe those docs pretty well. Certain tags have one of a pre-defined list of values ("restriction" in XML schema terms). To edit this, a drop-down list is a very handy thing. How would you populate that? Well an enum sure looks like an attractive thing and these days in Java, enums have come a long way so that you can give the enum a handful of properties.

So I copied each set of restricted values out of the XSD file into a Java file and created enums - dandy! The first small problem we created for ourselves is that the restricted values have dashes. Gosh, as enum identifiers dashes look a whole lot like minus signs. So now I have to map the XML value to the enum value somehow.



enum SensorType {
accelerator,
altimeter
}

But it's very easy to populate the combo box:



inputSensorCombo.setModel(new DefaultComboBoxModel(SensorType.values()));


So I have to add the mapper, but while I'm at it I would like to have a different
display value in the combo box that has blanks!


Still not a big problem - create the enum class with a display value and XML tag value:



enum SensorType {
accelerator("Accelerator", "accelerator"),
altimiter("Altimiter", "altimiter");
final String displayValue;
final String xmlTagValue;
SensorType(String displayValue, String xmlTagValue) {
this.displayValue = displayValue;
this.xmlTagValue = xmlTagValue
}
@Override
public String toString() {
return displayValue;
}
}



With the toString override, populating the combo box is still the same. Pretty good, yeah? Now, I have about 4 of those. We're OO so just make a base class, right? Sorry. As 'syntactic sugar' enum already extends Enum, so we're SOL.



Bummer. Let's try Scala.... next post.

1 comment:

Engineer Dude said...

Thanks to @siobhanquinn for turning me on to draft.blogger.com!
I do not know what causes the big gaps around the code.
FWIW, I spent much of the rest of the day downgrading to Scala 2.7.7 and trying to figure out which Scala Swing classes to use. Stay tuned - but don't hold your breath.