Archive for the Category UIs and Swing

 
 

Simplifying

I always find it healthy to come back and use code you wrote a while ago. There’s nothing like a bit of space to help see things in a new light. Often too you can be so focused on solving one problem that you don’t get a chance to step back and see the bigger picture.

And so it was when using my binding framework the other day. Don’t get me wrong, I really like it. But the first pass gave me flexibililty I needed, but not the simplicity I needed for day to day regular use. Who really wants to create presentation models using the following?

// somewhere at startup
Pectin.registerMixin(ComponentMixin.instance());

// then when you need a presentation model
PresentationModel<ComponentValueModel> pm =
      new PresentationModel<ComponentValueModel>();

// and use the "firstName" value model..
pm.get("firstName").setEnabled(false);

What’s a ComponentValueModel anyway and why do I need one? As it turns out I almost always want one (since it gives my value models the common enabled, visible, and editable properties) so why do I have to specify it every time? Then there’s validation, you almost always need that too.

So, short story long, I’ve layered the API. The original classes have been moved to a lower level (i.e. GenericPresentationModel) and I’ve created new implementations that extend them and that come pre-configured with the default interfaces. I’ve also installed the associated Mixins automatically so for everyday use it’s now just:

// This is much better
PresentationModel pm = new PresentationModel();
pm.get("firstName").setEnabled(false);

Much nicer.

Farewell Tapestry and Hello GWT

With the upcoming release of Tapestry 5 I’ve decided to take the plunge and try out GWT. I’ve long been a Tapestry fan (I can’t stand the goto development style of Struts), but this latest version has left me a little wanting. In short:

  • It’s changing dramatically again.
  • The framework now magically invokes methods if they follow particular conventions.
  • I hate method conventions. Intellij IDEA is really good at telling me all kinds of useful things. Method conventions bugger that up completely.
  • Tapestry documentation has always been lacking, this magnifies the previous gripe by a factor of 100.

Once I realised the depth of my grumpiness I decided to re-evaluate the webapp landscape. Since I’m not interested in ruby/rails I decided to give GWT a whirl.

The GWT approach is different. You don’t develop a web application with lots of pages etc, you write Javascript application which you then embed in a given web page (I.e. a bit like embedding an Applet in a page). While it’s not a solution for generating websites, it’s great for developing web applications.

What’s more, you write your Javascript in Java. Sweet. I get everything Java gives me (well a fair bit anyway) like packages, interfaces and type safe refactoring etc.

Some of the good points are:

  • The documentation is great. Well thought out and well written.
  • The shell environment is wonderful. The best out of the box web development experience I’ve had yet.
  • The client aspects of the application are written using standard client techniques. Observable models, reusable widgets, similar development approaches.
  • My server is stateless.

Things that could be better:

  • There’s no binding API. Life without binding sucks. There are apparently plans for one, but in the mean time it took me a week to migrate my Swing binding framework over to GWT.
  • It would be nice if there was an easier way to add servlet context listeners and context parameters to the shell environment.
  • Better documentation on writing compiler plugins would be nice.

Other than that, the combination of GWT in the browser and simple servlets using Guice on the backend has been a delight.

Playing with Google Guice: Look and Feel

In this example I’m showing how I use the LookAndFeelService in conjection with the EnvironmentService to configure the LAF defaults based on the runtime environment. The LookAndFeelModule allows me to configure various look and feel aspects based on the runtime environment.

The LookAndFeelModule is the starting point. You configure it and it configures the LookAndFeelService appropriately.

// create the module
LookAndFeelModule lafModule = new LookAndFeelModule();

// set the default look and feel.
lafModule.setDefaultLookAndFeel(UIManager.getSystemLookAndFeelClassName());

// now configure environment specific lafs
lafModule.registerLookAndFeel(MacOSX.class,
                              QuaquaLookAndFeel.class.getName());

I also use a replacement for JOptionPane that supports application wide and document specific option panes as required by the Mac. This too needs to be configured based on the environment we’re running on.

// Configure the MessagePaneProvider to use by default
lafModule.setDefaultMessagePaneProvider(new GenericMessagePaneProvider());

// now configure environment specific MessagePane providers
lafModule.registerMessagePaneProvider(MacOSX.class,
                                      new MacMessagePaneProvider());

Then I simply pass the module to my application launcher. The application retrieves the LookAndFeelService and invokes its configure method.

Launcher.launch(MyApplication.class, args, lafModule);

Of course instead of repeating this in every application I’ve created a default module implementation that’s preconfigured. So all I need do is:

Launcher.launch(MyApplication.class, args, new DefaultLookAndFeelModule());

And everything just works. Nice.

Playing with Google Guice: Splash Screens

The previous entry showed the creation of a (very) simple single frame application. Splash screens are common, so lets add one. Since there’s no easy way to do it for all occasions, we’ll use a Guice module to provide it for runtimes prior to Java 6.

public static void main(String[] args)
{
   URL splashImage = Main.class.getResource("/images/splash.png");

   // create the splash module for pre Java 6 runtimes.
   Module splashModule = Java5SplashScreenModule(splashImage);
   Launcher.launch(MyApplication.class, args, splashModule);
}

And that’s it. The framework will display the splash screen and all will work fine. Of course if you’re running on Java 6 you’d used the Java 6 version (that uses the new SplashScreen functionality). Of course if we don’t define the service in one of our modules, the framework uses the default `NullSplashScreenService`.

If MyApplicationFrame (or any other class for that matter) wanted to use the splash screen service, it just needs to inject it into it’s constructor.

public class MyApplicationFrame extends JFrame
{
   @Inject
   public MyApplicationFrame(SplashScreenService splashService)
   {
      // do stuff....
      splashService.setImageURL(nextImageURL);
   }
}

Playing with Google Guice

It’s been a long time coming but I’ve finally started dabbling in dependency injection for my swing frameworks. It’s taken me a quite a while to get a feel for where and how it can/should be used. Given the complexity of even an average Swing application I’d been loathed to convert all my UI construction and wiring over to a container, but I’d also love to create a framework environment where I can install all my standard behaviours in one line.

I’d also been wanting to consolidate my various frameworks and utilities into a single application framework (along the lines of JSR-296) but wanted to try out the dependency injection route.

Anyway, so far I’ve been very pleased with the results. I’ve been able to create services for controlling the splash screen, determining the runtime environment and providing runtime environment services, configuring Look and Feel settings and so on. With Guice you can easily create default implementations of your services so you can have the basics going with zero configuration.

So the following useless example shows what’s necessary to get a frame up and create a file in the default application data directory.

public class MyApplication
extends SingleFrameApplication
{
   public MyApplication()
   {
      super("MyApplication", MyApplicationFrame.class);
   }

   public void initialise(String[] args)
   {
      // The EnvironemntService ensures it's the correct location
      // based on the runtime platform.. i.e. `C:\AppData\MyApplication`
      // on windows and `~/Library/Application Support/MyApplication`
      // on the Mac.

      // AbstractApplication provides getters for standard services so
      // you don't have to magically discern their existence.
      EnvironmentService env = getEnvironmentServices();
      File logFile = env.getFileInAppDataDirectory("logs/my-app.log");

      // do stuff with the file...
      ....
   }
}

Then the application can be simply started using the following.

public static void main(String[] args)
{
   Launcher.launch(MyApplication.class, args);
}

Why I generally avoid GUI Builders

How’s that for a non committal title (c:

Most of my own thoughts have been better explained by others.  Beware the GUI Builder is an excellent article on Hacknot, and a response by Karsten Lentzsch to this post sums up the design issues well (search for “Karsten Lentzsch” and you’ll find his comment).

The meta design issues described by Karsten are a major sticking point for me. The implication is that if you use GUI builders and your UI design requires that the label/component gap be 4 DLUs, or that section titles should have 12 DLUs of top padding, then every developer must know every rule and ensure they implement it correctly on every form. You will have problems.

Custom layout builders on the other hand don’t generally suffer the same fate. They’re able to capture the design rules in one place (i.e. the DRY principle) and your developers can live blissfully unaware of the nitty gritty requirements or implementation issues.

For larger projects you can also specialise the builders and integrate them with other infrastructure such as a binding or command framework.

//  a trivial example that doesn't really make sense.
SimpleFormBuilder b = new SimpleFormBuilder();
b.setFormTitle("My Cool Form");
b.addTextField("First _Name", firstNameValueModel);

Of course the real problems with layout builders is that you have to design and write them, and there will always be cases that break the rules. You can minimize this pain however if you start with a decent builder and layer your architecture so developers can drop down to “manual” for the edge cases.

This then is the real issue for me: if you only have a few static screens, then a GUI builder is probably an acceptable option, but once your project grows you’re heading for trouble.

Playing with ANTLR

One aspect that can be annoying when creating value models creating bindings for their enabled and visible states. The following shows a simple example where certain components are enabled and disabled based on the value of others.

Mr Schedule Options

In this screen, the “Use Proxy” is only enabled when “Automatically Check for Updates” is selected, and both the “Host” and “Port” fields are only enabled when both check boxes are selected.

To simplify this kind of operation I’ve been playing around with ANTLR grammars. First off, if you’re like me and have never built a language parser before, just go ahead and buy the book. Building an abstract syntax tree would have been near impossible without it.

So far I’ve been able to get a basic language up and going. The syntax is simple and lets you assign model properties from simple expressions involving other models, for example:

useProxy.enabled = checkForUpdates.value

This binds the enabled property of “useProxy” to the value of “checkForUpdates”. I also let you omit the “.value” for simplicity, so then we get:

useProxy.enabled = checkForUpdates

So state of the all the components in the above image is controlled by the three “bind” lines of code in the PresentationModel.

// install the value models...
installValueModel("checkForUpdates", ..);
installValueModel("useProxy", ..);
installValueModel("proxyHost", ..);
installValueModel("proxyPort", ..);

// and create the bindings
bind("useProxy.enabled = checkForUpdates");
bind("proxyHost.enabled = checkForUpdates && useProxy");
bind("proxyPort.enabled = checkForUpdates && useProxy");

Normally I don’t like putting code in strings, but in this case I think it’s worth it. To limit any possible issues the library barfs during the call to bind if any of the models are missing or don’t define the required properties.

And then there were Mixins

One of the key goals for my binding infrastructure has been to make it easy to extend the value models to suit your business requirements. The idea was let you define a custom value model properties and have the library automatically manage them. I had this working pretty well, but it was pretty painful to set up, and definitely not something I’d wish on others.

Enter Mixins. Somewhere along the line it occurred to me that I could create Mixins that provide standard ValueModel extensions and their handlers out of the box. The first test was to convert my ComponentValueModel interfaces that defines standard component properties such as enabled, editable and visible.

public interface ComponentValueModel extends ValueModel
{
    @DefaultValue(true)
    public boolean isEnabled();
    public void setEnabled(boolean enabled);

    @DefaultValue(true)
    public boolean isEditable();
    public void setEditable(boolean editable);

    @DefaultValue(true)
    public boolean isVisible();
    public void setVisible(boolean visible);
}

Using this mixin is now as simple as..

// install the mixin that defines the ComponentValueModel
// interface and standard handlers.
Pectin.registerMixin(ComponentMixin.instance());

// create a presentation model that vends ComponentValueModels
pm = new BeanPresentationModel<Person, ComponentValueModel>(...);

// all the value models returned by the presentation model will
// implement the mixin interface.
ComponentValueModel cvm = pm.get("firstName");

// changes to the mixin properties will be automatically handled
// by the mixin
cvm.setEnabled(true);
cvm.setEditable(false);
cvm.setVisible(true);

From here the mixin is responsible for updating the state of components bound to ComponentValueModels. The mixin uses styles that map particular model properties to particular components allowing you to control the way particular properties effect particular components.

So far I’m really pleased with the progress.

More Value Model thoughts…

In light of my previous post, I’ve long pondered how I could create a generic PresentationModel/ValueModel framework that can be customised on a per project basis.

  1. Must be able to extend the ValueModel interface with real meta data methods.
  2. Must be able to modify the behaviour of the component bindings to use use the custom ValueModel metadata defined above.
  3. Must support buffering natively.
  4. Must be easy to use out of the box and easy to customise.

I’d had a couple of goes at this in the past but yesterday I had a bit of a moment where I believed it might be possible (either rightly or wrongly).

Ignoring any doubts I tried a few ideas and to my surprise it progressed pretty well. I think this was partly because I’d been spending more time away from the Mac where my brain could think in peace.

Anyway, I shall continue plugging away and see how it turns out.

Extending Value Models

I recently worked on a large scale Swing project where we made heavy use of value models in the UI. The requirements were complex as the interface designers were more interested in what was good rather than what was easy.

In our technology selection we examined various value model frameworks such as Spring Rich Client, JGoodies Binding and PGS Binding. Of all the frameworks we examined, none provided a simple mechanism for adding meta data to our value models.

Some of our meta data included the following properties:

  1. Obfuscated - some fields need to be be obfuscated from view (such as credit card numbers) based on the users profile.
  2. These fields also needed the ability to be un-obfuscated temporarily.
  3. Editable - Some fields needed to be displayed, but were only editable if the user had the required privileges. Non editable fields looked like labels and not like regular components.
  4. Enabled - Fields that were editable could be either enabled or disabled.
  5. Visible - Fields and forms needed to be shown and hidden.

Even if we could find a framework that could model these aspects it would be unlikely that it would match the exact look and feel requirements of our designers. So in the end, we decided to write our own.

Our approach was to use the ValueModel as both and Adapter and Decorator. As an adapter the value model was responsible for transfering the value to and from the source. As a decorator it provided additional information about the value that was relevant for the UI.

Binding Overview

The key to the design was that the infrastructure modeled our business requirements. In the end developers had very little code to write to create a whole dollar, obfuscated `JFormattedTextField`, and none of it was difficult or Swing-ish.