views:

507

answers:

2

I am stuck in binding values from enum to RadioButton. Lets say I have a bean:

public class ValueObject {
  public enum ValueEnum {
    FIRST_VALUE,
    SECOND_VALUE
  }

  protected ValueEnum value;
}

I want to create Swing RadioButtons where user can select one from these two enum values. As I use Netbeans as IDE I would also like to do it using data binding, ie. bind radio buttons to {valueObject.value}. Any ideas? Thanks a lot!

A: 

I'd say it won't work. Usually you create a binding between widget and a variable. Your widget is a two state radio button, so you would bind it to a boolean variable. As a result of that binding, if you press the button, the boolean variable changes to true, if the button becomes deselected, the boolean variable goes back to false.

With JFace databinding you would implement a converter, that would convert between boolean and the two enum values. That converter would be part of the databinding (you can add validators and converters). Unfortunatly I haven't done it with Swing or netbeans, but the approach should be similar: you either add a converter to the binding or you have to bind to a boolean variable and do the conversion (mapping) afterwards.

Andreas_D
+1  A: 

Whow, the converter was a great idea! I created the converter below and initialized it with the enum value.

public class ObjectEqualityConverter extends Converter {

    private Object o;

    public ObjectEqualityConverter() {}

    public ObjectEqualityConverter(Object o) {
        this.o = o;
    }

    public Object convertForward(Object value) {
        return (o != null && o.equals(value)) ? Boolean.TRUE : Boolean.FALSE;
    }

    public Object convertReverse(Object value) {
        return (Boolean.TRUE.equals(value)) ? o : null;
    }
}
sax
Exactly! Glad to hear that it worked :-)
Andreas_D