Wednesday 15 February 2012

SwingBuilder Series: Table (I)

Tables are the most common topics when talking about data. Groovy makes table creation really simple.

The following example just gives an idea of the ease of creation of a table with SwingBuilder, if you need to create something complex I really recommend you to use SwingBuilder along with the GlazedLists library.

Let's create a view model class for creating instances to add to our table
class Event{
String title
String speakerName
}

Then let's build a form with some fields, and of course the table and its model:

panel{
vbox{
panel{
gridLayout(rows:5,columns:1)
label("Title")
textField(id:'title',action:addAction)
label("Speaker Name")
textField(id:'speakerName',action:addAction)
button(id:'add',action:addAction)
}
scrollPane{
table(id:'eventsTable'){
tableModel{
propertyColumn(header: "Event Title" ,propertyName: 'title')
propertyColumn(header: "Speaker Name" ,propertyName: 'speakerName')
}
}
}
}
}
It's very important to wrap tables inside a scrollPane because table's headers are painted in the header area of the scroll panel.

The table node (table()) has many properties you can check out here. In this example I'm only interested in table's models rather than the table itself.

Inside the table there's a table model (tableModel()) and inside the table model there're a couple of propertyColum() nodes. The propertyColumn nodes, are very useful...
  • to create the table's headers (header:'Event title')
  • to tell the way the column is going to be rendered (see cellRenderer property)
  • to tell what is the property this column represents (propertyName:'title')
Finally the action to add the form field values to our table.
def addAction = action(
id:'add',
name:'Add to Table',
closure:{
eventsTable.model.with{
rowsModel.value.add(
new Event(
title:title.text,
speakerName:speakerName.text
)
)
fireTableDataChanged()
}
}
)
This action gets the values from the form fields and creates a new Event instance with all those values. Once the button has been pressed the Event is added to the table through the rowsModel property.

Finally don't forget to call fireTableDataChanged() or your data won't be visible!


1 comment:

  1. Hola oyes tiene muy buen contenido tu blog, no mas que tengo una pequeña observacion podias poner un menu o algo para ver todo el contenido

    Saludos

    ReplyDelete