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)?

ぃ、小莉子 提交于 2019-12-24 02:57:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5948147/how-can-i-bind-a-property-e-g-an-enum-to-a-component-property-of-a-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!