Nick's Tech Blog: Groovy > Bidirectional binding using SwingBuilder

Pages

Friday, May 10, 2013

Groovy > Bidirectional binding using SwingBuilder

Problem

I was trying to setup "two-way" binding (e.g. model can update the ui, and vice versa), in a single bind{} statement.

For example, the below code is exhibiting the "two-way" binding behaviour that I want (i.e. toggleButton <-> model.toggleButtonValue). I was wondering if there was a more succinct way to get the same behaviour, but without having two statements (i.e. without the need to have the actionPerformed)?
toggleButton('Test',
  selected: bind { model.toggleButtonValue }, // model->button
  actionPerformed: { model.toggleButtonValue = button.selected }) // button->model

So I posted on the Groovy forums, and got the following answer from Ed Clark (Thanks Ed!)

Solution

Just use the "mutual" flag, like in the following examples:

toggleButton('Test',
  selected: bind (source: model, 'toggleButtonValue', mutual: true))

// Fyi, the following also works, but the button will ignore the
// model's value on initialisation.
toggleButton('Test', selected: bind (target: model, 'toggleButtonValue', mutual: true))

As far as I know, it's an undocumented feature at the moment. I couldn't find it on the SwingBuilder.bind site/docs.

See Also:
My Original Problem on the Groovy Forums

No comments:

Post a Comment