在 javaFX 中将 DoubleBinding 转换为 double
Converting DoubleBinding into double in javaFX
DoubleBinding angle = new SimpleDoubleProperty(myIndex*Math.PI*2).divide(nrMoons);
moon.centerXProperty().bind(earth.centerXProperty().add(Math.cos(angle.doubleValue()).multiply(RADIUS_ORBIT)));
那是我的代码的一部分,在那里我得到一个错误,即 double angle.doubleValue() 不能被取消引用,并且 Math.cos() 需要double 不是 DoubleBinding,知道如何转换它吗?
假设你要加的数量是角度余弦和RADIUS_ORBIT
的乘积,你只需要使用运算符*
而不是函数multiply
:
moon.centerXProperty().bind(earth.centerXProperty().add(Math.cos(angle.doubleValue()) * RADIUS_ORBIT));
请注意,这可能不会按照您想要的方式工作:您传递给 add(...)
的值不可观察(它只是一个普通的 double
),因此该值只会在以下情况下更新earth.centerXProperty()
更改,但如果 angle
更改则不会更新。这不是因为使用 *
而不是 multiply()
,而是因为 Math.cos()
returns 是普通的 double
而不是某种 ObservableDoubleValue
.在 JavaFX properties/bindings 中没有针对 "taking the cosine of a value" 的直接 API。
如果您希望它动态地依赖于 angle
,您应该使用自定义绑定(这还具有使计算更容易在代码中看到的优点)。
我想这是你要计算的值:
moon.centerXProperty.bind(Bindings.createDoubleBinding(() -> {
double earthCenter = earth.getCenterX();
double offset = Math.cos(angle.get()) * RADIUS_ORBIT ;
return earthCenter + offset ;
}, earth.centerXProperty(), angle);
DoubleBinding angle = new SimpleDoubleProperty(myIndex*Math.PI*2).divide(nrMoons);
moon.centerXProperty().bind(earth.centerXProperty().add(Math.cos(angle.doubleValue()).multiply(RADIUS_ORBIT)));
那是我的代码的一部分,在那里我得到一个错误,即 double angle.doubleValue() 不能被取消引用,并且 Math.cos() 需要double 不是 DoubleBinding,知道如何转换它吗?
假设你要加的数量是角度余弦和RADIUS_ORBIT
的乘积,你只需要使用运算符*
而不是函数multiply
:
moon.centerXProperty().bind(earth.centerXProperty().add(Math.cos(angle.doubleValue()) * RADIUS_ORBIT));
请注意,这可能不会按照您想要的方式工作:您传递给 add(...)
的值不可观察(它只是一个普通的 double
),因此该值只会在以下情况下更新earth.centerXProperty()
更改,但如果 angle
更改则不会更新。这不是因为使用 *
而不是 multiply()
,而是因为 Math.cos()
returns 是普通的 double
而不是某种 ObservableDoubleValue
.在 JavaFX properties/bindings 中没有针对 "taking the cosine of a value" 的直接 API。
如果您希望它动态地依赖于 angle
,您应该使用自定义绑定(这还具有使计算更容易在代码中看到的优点)。
我想这是你要计算的值:
moon.centerXProperty.bind(Bindings.createDoubleBinding(() -> {
double earthCenter = earth.getCenterX();
double offset = Math.cos(angle.get()) * RADIUS_ORBIT ;
return earthCenter + offset ;
}, earth.centerXProperty(), angle);