将 DoubleBinding 转换为 double 在 JavaFX 中

huangapple go评论144阅读模式
英文:

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.get()) * RADIUS_ORBIT));
英文:
DoubleBinding angle = new SimpleDoubleProperty(myIndex*Math.PI*2).divide(nrMoons);
moon.centerXProperty().bind(earth.centerXProperty().add(Math.cos(angle.doubleValue()).multiply(RADIUS_ORBIT))); 

that is the part of my code, where I get an error that double angle.doubleValue() cannot be dereferenced, and Math.cos() requires a double not a DoubleBinding, any idea on how to convert it?

答案1

得分: 2

假设您想要添加的数量是角度的余弦和 RADIUS_ORBIT 的乘积,您只需要使用运算符 *,而不是函数 multiply

moon.centerXProperty().bind(earth.centerXProperty().add(Math.cos(angle.doubleValue()) * RADIUS_ORBIT));

请注意,这可能不会按您所希望的方式工作:传递给 add(...) 的值不可观察(它只是一个普通的 double),因此该值只会在 earth.centerXProperty() 更改时更新,但在 angle 更改时不会更新。这不完全是因为使用 * 而不是 multiply(),而是因为 Math.cos() 返回的是普通的 double,而不是某种 ObservableDoubleValue。在 JavaFX 属性/绑定中没有直接的 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));
英文:

Assuming the quantity you want to add is the product of the cosine of the angle, and RADIUS_ORBIT, you just need to use the operator * instead of the function multiply:

moon.centerXProperty().bind(earth.centerXProperty().add(Math.cos(angle.doubleValue()) * RADIUS_ORBIT));

Note that this probably won't work the way you want: the value you pass to add(...) is not observable (it's just a plain double), so the value will only update if earth.centerXProperty() changes, but won't update if angle changes. This is not so much because of using * instead of multiply(), but because Math.cos() returns a plain double instead of some kind of ObservableDoubleValue. There's no direct API in JavaFX properties/bindings for "taking the cosine of a value".

If you want this to depend dynamically on angle, you should use a custom binding (which also has the advantage of making the computation easier to see in the code).

I think this is the value you want to compute:

moon.centerXProperty.bind(Bindings.createDoubleBinding(() -> {
    double earthCenter = earth.getCenterX();
    double offset = Math.cos(angle.get()) * RADIUS_ORBIT ;
    return earthCenter + offset ;
}, earth.centerXProperty(), angle);

huangapple
  • 本文由 发表于 2020年6月5日 21:33:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/62216565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定