Sunday 19 February 2012

SwingBuilder Series: Table (II) : A Simple CellRenderer


This time I'm gonna improve a little bit my table. I want the boolean values to have a specific background depending on its value: green for true and red for false.

First of all here I need some imports:


import java.awt.*
import javax.swing.table.*
import javax.swing.*

Now my Event object has one more property to tell me whether the event is still running or it's over. To do this job I'm gonna create a renderer for the alive property.
  class BooleanRenderer extends DefaultTableCellRenderer{
Component getTableCellRendererComponent(
JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {
def label = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column)
label.background = value ? java.awt.Color.GREEN : java.awt.Color.RED
label
}
}

This render is pretty basic, it only gets the default
component which is a JLabel and then it turns it g
reen when the value is true and red when the value is false. To do it perfect, the method has to take into account a few things more (isSelected, hasFocus).

The rest is almost the same thing, the node compo
nents:

panel{
vbox{
panel{
gridLayout(rows:6,columns:1)
label("Title")
textField(id:'title',action:addAction)
label("Speaker Name")
textField(id:'speakerName',action:addAction)
hbox{ label("Alive ?")
checkBox(id:'alive')
}
button(id:'add',action:addAction)
}
scrollPane{
table(id:'eventsTable'){
tableModel{
propertyColumn(header: "Event Title" ,propertyName: 'title')
propertyColumn(header: "Speaker Name" ,propertyName: 'speakerName')
propertyColumn(
header: "Alive ?" ,
propertyName: 'alive',
cellRenderer: new BooleanRenderer()
)
}
}
}
}
}




And the action to add each event.


def addAction = action(
id:'add',
name:'Add to Table',
closure:{
eventsTable.model.with{ rowsModel.value.add(
new Event(
title:title.text,
speakerName:speakerName.text,
alive: alive.selected
)
)
fireTableDataChanged()
}
}
)

And voila:

No comments:

Post a Comment