Wolfmans Howlings

A programmers Blog about Programming solutions and a few other issues

Groovy bean dialogs

Posted by Jim Morris on Tue Feb 21 16:36:46 -0800 2012

I really wanted to share this one as it is so cool.

I have been writing some database GUI admin tools using Groovy and I use SwingBuilder to build the UI as it tends to be easier than using Swing directly.

Inspired by the Eclipse Windows Builder ability to generate a JDialog from a bean, I figured that Groovy/Swingbuilder should be able to do the same thing dynamically.

So sure enough here is my Groovy Bean Dialog. Basically take a normal Groovy bean, and have it extend BeanDialog, and you get a showDialog() call that will display a JDialog with all the bean fields nicely labeled and layed out. As the Groovy Bean has @Bindable on all the fields, you can set the field before the dialog is displayed and then edit the fields and get the changes when the dialog is disabled. All in very few lines of code.

This opens up the ability to easily create dialogs to get input as well...

then to get the dialog...

Sample Dialog

This is also great for displaying data from databases, just get the data from the table, and populate the Groovy Bean from a map of the data, and display the dialog. Remember that Groovy beans can be passed a Map in the constructor, and it will populate the beans with the fields that match the map keys.

An example for the above bean would be...

Note I use MigLayouty to simplify the layout issues, it does a great job of pairing up the labels and textfields, with very little setup.

As a bonus you get a toString() that prints out all the fields/properties.

Posted in Java,Groovy,SwingBuilder  |  Tags groovy,swingbuilder  |  1 comments

Comments

  1. Hutch said on Sat May 02 12:50:30 -0700 2015
    Nice little piece of code - solved my problem nicely. Thanks

(leave email »)