binding - 如何绑定(bind)两个不同的 JavaFx 属性 : String and Double (with StringConverter)?

标签 binding properties javafx

对于这段代码(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/

相关文章:

java - 如何在 JavaFx 上创建 Desplegable 列表?

binding - ExtJs 5 网格存储/ View 模型绑定(bind) : Cannot modify ext-empty-store

wpf - 在 VisualState Storyboard 中使用绑定(bind)

c++ - Boost 捆绑属性 : Do I need to initialize all properties for each edge?

jenkins - Post-build Actions 部分看不到注入(inject)的环境变量

string - 变体记录中的短字符串?

javafx - 如何正确使用高对比度主题?

java - 如何在 Gomoku javafx 游戏中启用轮流

javascript - 如何为 javascript 调整工作的 html Angular 过滤器

c# - WPF 将应用程序命令绑定(bind)到 ViewModel ICommand