Thursday, February 11, 2010

Add Rows to Groovy's Swing Builder DefaultTableModel

If you've had an opportunity to mess around with Groovy's Swing Builder, you may have noticed that the table model used for tables is not the standard javax.swing.table.DefaultTableModel, but is an instance of groovy.model.DefaultTableModel. Java's implementation of the DefaultTableModel has an addRow() method that allows the addition of new rows, however Groovy's implementation does not.

This left me, and many others, wondering how to go about adding a new row to Groovy's DefaultTableModel object. After looking over the Groovy API, I have come up with the solution below. Enjoy:

import groovy.swing.SwingBuilder

def swing = new SwingBuilder()
def tableData = [ [firstName: "Bob", lastName: "Stevens"], [firstName: "Lucy", lastName: "House"] ]
def myTable = swing.table(){
tableModel( list:tableData ){
propertyColumn( header:"First Name", propertyName:"firstName" )
propertyColumn( header:"Last Name", propertyName:"lastName" )
}
}

// Let's add a new row to the table
def rows = myTable.getModel().getRowsModel().getValue()
rows.add( [ firstName: "Reese", lastName: "Smith" ] )
myTable.getModel().getRowsModel().setValue( rows )
myTable.getModel().fireTableDataChanged()

This example will add a new row to the end of the table and then redraw the JTable so the new row will show up. The function getRowsModel() returns the ValueModel which allows you to manipulate the data within the table. The value set within the ValueModel will be a list of the rows in the table and you can add rows by calling add( rowData ) or specify an index with add( index, rowData ) to allow you to insert data at a specific spot in the list.

1 comments:

Brock Heinz said...

Just what I was looking for. Thanks!

Just curious - where can you find any documentation for the 'tableModel' implicit constructor where you're passing a native map with 'list'?

I found it my GiNA book, but it's definitely not here

© 2010 Confessions of a Java Programmer, All Rights Reserved