Groovy has some very nice builders to quickly make for example XML. The SwingBuilder
class makes it possible to use a builder syntax to make a GUI. We define the components we want to display, bindings, and event handlers. Groovy adds the TableLayout as a layout manger to define a simple table-like layout.
import groovy.swing.SwingBuilder import groovy.beans.Bindable import static javax.swing.JFrame.EXIT_ON_CLOSE import java.awt.* @Bindable class Address { String street, number, city String toString() { "address[street=$street,number=$number,city=$city]" } } def address = new Address(street: 'Evergreen Terrace', number: '742', city: 'Springfield') def swingBuilder = new SwingBuilder() swingBuilder.edt { // edt method makes sure UI is build on Event Dispatch Thread. lookAndFeel 'nimbus' // Simple change in look and feel. frame(title: 'Address', size: [350, 230], show: true, locationRelativeTo: null, defaultCloseOperation: EXIT_ON_CLOSE) { borderLayout(vgap: 5) panel(constraints: BorderLayout.CENTER, border: compoundBorder([emptyBorder(10), titledBorder('Enter your address:')])) { tableLayout { tr { td { label 'Street:' // text property is default, so it is implicit. } td { textField address.street, id: 'streetField', columns: 20 } } tr { td { label 'Number:' } td { textField id: 'numberField', columns: 5, text: address.number } } tr { td { label 'City:' } td { textField id: 'cityField', columns: 20, address.city } } } } panel(constraints: BorderLayout.SOUTH) { button text: 'Save', actionPerformed: { println address } } // Binding of textfield's to address object. bean address, street: bind { streetField.text }, number: bind { numberField.text }, city: bind { cityField.text } } }
When we run the script we get the following output:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEid1JekbT_eMFIAE1D18AAmAK68cqvw7WIXNVFaz0pTboUjHjYL2G3rhxqLd7-_6-knzNAw6lPhfZ85jsQcvGHq07WUy2NHCEOjgAnSwLQmqWOj9WN6pKpin4CpWuxpGQZ5NAMzm-oNSw_o/s320/blog-gg-swing1.png)
If we change the input field and click on the Save button we get the following output:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnwsCXco2IWbFQvN_Itn-P0kjGw9t-fh186CfVGJEi9tHPq6ZN3xG5ZZPPCG0nucNy1A2UkYhbL_fQ4Bj2sxgAGIiXWik36_xVe_njQYJa-Y1_3Vp0AcDiDqQtBghQoPhiz2M4WNMHzjzN/s320/blog-gg-swing2.png)
address[street=Main St.,number=1,city=Hometown]