Sunflame:
私は本当に1双方向ではなく、2 DoublePropertyをバインドしたい:1、しかし1で、たとえば:1.2の割合。
私のようなものが必要になります。
DoubleProperty x;
DoubleProperty y;
x.bindBidirectional(y.multiply(1.2));
値が毎回ので、xが設定され、yの値がある必要があり、X * 1.2と毎回yの値は、xがあるべき設定されているY / 1.2
どのように私はそれを行うことができますか?
ファビアン:
あなたはこのあなたのようなinplement何かに必要なので、私の知る限り何もexistanceにすでに存在しません。
public abstract class BidirectionalBinding<S, T> {
protected final Property<S> property1;
protected final Property<T> property2;
protected boolean calculating = false;
private final InvalidationListener listener;
/**
* Convert value for property 1 to value for property 2
*
* @param value
* @return
*/
protected abstract T convert(S value);
/**
* Convert value for property 2 to value for property 1
*
* @param value
* @return
*/
protected abstract S inverseConvert(T value);
protected BidirectionalBinding(Property<S> property1, Property<T> property2) {
if (property2.isBound() || property1 == null) {
throw new IllegalArgumentException();
}
this.property1 = property1;
this.property2 = property2;
property2.setValue(convert(property1.getValue()));
listener = o -> {
if (!calculating) {
calculating = true;
try {
if (o == property1) {
T value = convert(property1.getValue());
property2.setValue(value);
} else {
S value = inverseConvert(property2.getValue());
property1.setValue(value);
}
} catch (Exception ex) {
dispose();
}
calculating = false;
}
};
property1.addListener(listener);
property2.addListener(listener);
}
public void dispose() {
property1.removeListener(listener);
property2.removeListener(listener);
}
}
DoubleProperty x = new SimpleDoubleProperty(3);
DoubleProperty y = new SimpleDoubleProperty();
final double factor = 1.2;
BidirectionalBinding<Number, Number> binding = new BidirectionalBinding<>(x, y) {
@Override
protected Number convert(Number value) {
return value.doubleValue() * factor;
}
@Override
protected Number inverseConvert(Number value) {
return value.doubleValue() / factor;
}
};
System.out.printf("x = %f; y = %f\n", x.get(), y.get());
x.set(5);
System.out.printf("x = %f; y = %f\n", x.get(), y.get());
y.set(15);
System.out.printf("x = %f; y = %f\n", x.get(), y.get());
この実装は一般化されることに注意してください。あなたにしているが、特殊な性質を扱う場合は、ラッパー型への変換を避けるために、プリミティブ型を使用するコードを変更したいことがあります...