对于这段代码(JavaFX)。
StringProperty sp;
DoubleProperty dp;
StringConverter<Double> converter = new DoubleStringConverter();
Bindings.bindBidirectional(sp, dp, converter);
我收到编译错误(在 Eclipse IDE 中)
这是方法签名:
public static <T> void bindBidirectional(Property<String> stringProperty, Property<T> otherProperty, StringConverter<T> converter)
但是,如果我删除(StringConverter 的)参数化,那么我只会收到警告并且代码有效。
StringConverter converter = new DoubleStringConverter();
我试图避免使用原始类型的泛型,这样我就不必在我的 IDE 中抑制警告。
So the question is:
What is the right pattern to write this piece of code?
最佳答案
这可能是 JavaFX 属性中的一个小“陷阱”。如果你仔细看签名:
static <T> void bindBidirectional(Property<java.lang.String> stringProperty,
Property<T> otherProperty, StringConverter<T> converter)
转换器的参数必须与属性的参数匹配。但是(这里的惊喜)
DoubleProperty
实现 Property<Number>
,因此 bindBidirectional
中的不匹配.幸运的是,解决方案很简单:使用 NumberStringConverter
:StringProperty sp = ...;
DoubleProperty dp = ...;
StringConverter<Number> converter = new NumberStringConverter();
Bindings.bindBidirectional(sp, dp, converter);
您可以获得额外的好处,即您可以指定转换格式。
关于binding - 如何绑定(bind)两个不同的 JavaFx 属性 : String and Double (with StringConverter)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21450328/