我怎样才能绑定属性(例如枚举),以不同类型(例如每个枚举的图像)的一个组成部分的财产? [英] 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)?
问题描述
我继承了使用JGoodies数据绑定到域模型连接到GUI的项目。不过,也有,我发现这也导致了一些错误一些不一致的地方。
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.
在这个具体的例子,该GUI是重新通过两个单选按钮和标签psented $ P $。根据选择了哪个按钮,标签应显示一定的图像。按钮被绑定到不同的枚举值,如:
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.
我的问题是:我怎么能这个属性绑定到由标签显示的图像
这是我所看到的,JGoodies数据是极好的结合就像琴弦的东西文本字段,但在这种情况下,也应该有一个转变,其中一些决定逻辑枚举属性映射到图像。
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.
推荐答案
好像我只是不得不采取绑定API中一探究竟。一个 AbstractConverter
正是我一直在寻找。
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));
的绑定
方法绑定pictureLabel的图标,通过转换器描述的模型。该转换器看起来是这样的:
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");
}
}
的 convertFromSubject
的方法是从哪儿来枚举形象改造已经完成。我没有落实的setValue
,因为它使得在这种情况下,没有任何意义。图像无法改变自己的,我只是想更新一条路可走 - 从枚举属性图片
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.
这篇关于我怎样才能绑定属性(例如枚举),以不同类型(例如每个枚举的图像)的一个组成部分的财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!