Search code examples
javaswingjgoodies

JGoodies: Binding multiple swing components to a single model field


I'm trying to create a "duration" field on a swing gui I'm developing. To do this, I've got 3 JSpinner components. Days, Hours and Minutes.

JSpinner durationDaySpinner;
JSpinner durationHourSpinner;
JSpinner durationMinuteSpinner;

If possible I'd like to "bind" these 3 components back to a single domain field:

long durationInMs;

i.e.

durationInMs = days*24*60*60*1000 + hours*60*60*1000 + minutes*60*1000;

Can anyone advise how I'd get this working with JGoodies binding? I've only ever bound single components to model/domain fields.

Cheers


Solution

  • You'd have to add a separate ValueModel for each spinner, bind each ValueModel to the appropriate spinner, then add a one PropertyChangeListener to all three ValueModels. When the value held by any of the three spinner-bound ValueModels changes, grab each value, calculate the ms like you've done in the question, and set that on the bean property (or ValueModel) you want to set.

    Essentially you're adding another mini-model between the domain model you're binding into and the UI model in order to map multiple UI-bound components onto a single domain property.

    Also, for readability I'd suggest using the java.util.concurrent.TimeUnit rather than lots of multiplications.

    Eg,

    long ms = TimeUnit.DAYS.toMillis(days) + TimeUnit.HOURS.toMillis(hours) + TimeUnit.MINUTES.toMillis(minutes);