Search code examples
javabindingjgoodies

How can I bind a property (e.g. an Enum) to a component property of a different type (e.g. an image for each Enum)?


I have inherited a project that uses JGoodies Binding to connect the domain model to the GUI. However, there are some inconsistencies that I have found which also cause some bugs.

In this concrete case, the GUI is represented by two radio buttons and a label. Depending on which button is selected, the label should display a certain image. The buttons are bound to different Enum values, like this:

AbstractValueModel enumSelectionModel = presentationModel.getModel("selection");

radioBtn1 = BasicComponentFactory.createRadioButton(enumSelectionModel,
        Selection.selection1, "");

radioBtn2 = BasicComponentFactory.createRadioButton(enumSelectionModel,
        Selection.selection2, "");

"selection" is the bound property, and Selection is the Enum, which means that when a different button is changed, the selection property in my model is set to the corresponding Enum value.

My question is: How can I bind this property to the image displayed by the label?

From what I saw, JGoodies is excellent for binding things like strings to text fields, but in this case, there should also be a transformation, some logic which decides maps the enum property to the image.


Solution

  • Seems like I just had to take a closer look in the Binding API. An AbstractConverter is exactly what I was looking for.

    Bindings.bind((JComponent) pictureLabel, "icon", new EnumToIconConverter(enumSelectionModel));
    

    The bind method binds the pictureLabel's icon to the model described by the converter. The converter looks like this:

    class EnumToIconConverter extends AbstractConverter {
    
        EnumToIconConverter(ValueModel subject) {
            super(subject);
        }
    
        @Override
        public Object convertFromSubject(Object enum) {
            return enum == Selection.selection1 ? image1 : image2;
        }
    
        @Override
        public void setValue(Object obj) {
            throw new UnsupportedOperationException("setValue makes no sense for this converter");
        }
    }
    

    The convertFromSubject method is where the transformation from Enum to image is done. I didn't implement setValue because it makes no sense in this case. The image cannot change on its own, I only want updates to go one way - from the enum property to image.