Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind two different JavaFx properties: String and Double (with StringConverter)?

For this piece of code (JavaFX).

StringProperty sp;
DoubleProperty dp;

StringConverter<Double> converter = new DoubleStringConverter();    

Bindings.bindBidirectional(sp, dp, converter);

I get compilation error (in Eclipse IDE)

This is the method signature:

public static <T> void bindBidirectional(Property<String> stringProperty, Property<T> otherProperty, StringConverter<T> converter)

But if I remove parametrization (of StringConverter), then I get only warnings and code works.

StringConverter converter = new DoubleStringConverter();    

I am trying to avoid to use raw type of generics so that I don't have to suppress warnings in my IDE.

So the question is:
What is the right pattern to write this piece of code?

like image 867
TurboFx Avatar asked Jan 30 '14 07:01

TurboFx


People also ask

What are binding properties used for in JavaFX?

JavaFX properties are often used in conjunction with binding, a powerful mechanism for expressing direct relationships between variables. When objects participate in bindings, changes made to one object will automatically be reflected in another object. This can be useful in a variety of applications.

What is double property JavaFX?

public static DoubleProperty doubleProperty(Property<Double> property) Returns a DoubleProperty that wraps a Property and is bidirectionally bound to it. Changing this property will result in a change of the original property. This is very useful when bidirectionally binding an ObjectProperty and a DoubleProperty.


1 Answers

This is probably a small "trap" in JavaFX properties. If you look closely at the signature:

static <T> void bindBidirectional(Property<java.lang.String> stringProperty,
    Property<T> otherProperty, StringConverter<T> converter)

The parameter of the converter must match the parameter of the property. But (the surprize here) DoubleProperty implements Property<Number>, thus the mismatch in bindBidirectional. Luckily the solution is simple: use NumberStringConverter:

StringProperty sp = ...;
DoubleProperty dp = ...;
StringConverter<Number> converter = new NumberStringConverter();
Bindings.bindBidirectional(sp, dp, converter);

You get the extra benefit that you can specify the conversion format.

like image 183
Nikos Paraskevopoulos Avatar answered Sep 29 '22 12:09

Nikos Paraskevopoulos