我试图使用JGoodies绑定2.9.1将JTextField
的enabled
属性绑定到枚举属性。我希望这是一个单向操作:当属性发生变化时,我想让JTextField
变为启用或禁用状态,但我绝不想以其他方式设置基于enabled
值的枚举属性。使用JGoodies绑定的只读绑定和单向转换器
尽管我认为我设置了一切正常,但我得到一个PropertyAccessException:未能设置适应的Java Bean属性。
我的模型是一个标准的Java Bean有属性更改事件:
public static String MY_PROPERTY = "myProperty";
private MyEnum myProperty;
public MyEnum getMyProperty() { return myProperty; }
public void setMyProperty(final MyEnum newValue) {
final MyEnum oldValue = myProperty;
if (newValue == oldValue) { return; }
myProperty = newValue;
changeSupport.firePropertyChange(MY_PROPERTY, oldValue, newValue);
}
在我看来,我有一个单向转换器,将返回true时绑定的值所提供的值相匹配:
private final class EnumMatchToEnabledConverter implements BindingConverter<MyEnum, Boolean> {
private MyEnum match;
public EnumMatchToEnabledConverter (MyEnum match) {
this.match = match;
}
@Override
public Boolean targetValue(MyEnum source) {
return (source == match);
}
@Override
public MyEnum sourceValue(Boolean target) {
// this wouldn't make sense
throw new UnsupportedOperationException();
}
}
然后我设置的结合:
PresentationModel<MyModel> pm = new PresentationModel<MyModel>(model);
Bindings.bind(
myTextField, "enabled", new ConverterValueModel(
pm.getModel(MyModel.MY_PROPERTY),
new EnumMatchToEnabledConverter(MyEnum.MyValue)));
令我惊讶的是,EnumMatchToEnabledConverter
的sourceValue()
方法被调用,并且因为它引发了UnsupportedOperationException
我从绑定中获得PropertyAccessException
。
我也试过明确告诉绑定不使用二传手,但我仍然有相同的行为:
Bindings.bind(
myTextField, "enabled", new ConverterValueModel(
pm.getModel(MyModel.MY_PROPERTY, "getMyProperty", null), // null setter!
new EnumMatchToEnabledConverter(MyEnum.MyValue)));
我要去哪里错了?
别人似乎已经成功地这样做:http://stackoverflow.com/questions/5948147/how-can-i-bind-a-property-eg-an-enum-to-a-部件属性对的一-不同 –