Tuesday 21 February 2012

SwingBuilder Series: Binding (II)


This entry is quite similar from the previous one, but here we're using the binding form:

bind(source,sourceProperty,target,targetProperty)

This way we're binding one property from the object triggering events to a destination object which receives values in the specified property. Here's the code:

import javax.swing.*
import groovy.beans.Bindable

@Bindable
class Event{
String title
String speaker
}

def event = new Event()

panel(id:'eventPanel',border:BorderFactory.createEmptyBorder(10,10,10,10)){
gridLayout(rows:5,cols:1)
label("Title")
textField(id:"title")
bind(
source:title,
sourceProperty:'text',
target:event,
targetProperty:'title'
)
label("Speaker")
textField(id:"speaker")
bind(
source:speaker,
sourceProperty:'text',
target:event,
targetProperty:'speaker'
)
button(
id:'submit',
text:'Send Event Info',
enabled: bind{event.title && event.speaker},
actionPerformed:{
JOptionPane.showMessageDialog(
eventPanel,
"Event: ${event.title} by ${event.speaker}"
)
}
)
}





In the example event properties are populated thanks to the bind() nodes. Those nodes wire text properties from textfields and properties from the event instance.

In the example we had Event class annotated as Bindable. If we only wanted event properties to be populated with the text fields, that wouldn't be necessary. But the button is enabled only if all the event properties are populated. That's why I've annotated the Event class as Bindable, because I wanted the event properties to trigger events as well.




No comments:

Post a Comment