将JavaFx标签绑定到根据三个节点属性更改的函数输出

问题描述 投票:1回答:1

我想让一个Label textProperty绑定到一个函数的值,该函数将采用一个节点数组(即三个线节点),然后根据节点的位置属性(即startXProperty)进行一些计算,这样每当节点的位置改变时,Label文本将相应地更新。

这是我的尝试:

Label label = new Label();

DoubleProperty myFunction(Line[] lines){

      DoubleProperty property= new SimpleDoubleProperty();

      // This is a sample computation, because the actual computation is much more complex. 
      // That's why I tried to avoid using the arithmetic methods provided by the Property class,
      // i.e., property().add().multiply()

      double computation = Math.sqrt(Math.pow(lines[0].startXProperty().getValue() - lines[1].startXProperty().getValue());

      property.setValue(computation);

      return property;
}

label.textProperty().bind(myFunction(lines).asString());

这种方法不起作用。我正在寻找解决这个问题的方法。谢谢!

javafx javafx-8
1个回答
1
投票

更新:解决了

感谢评论中提供的答案,我更改了函数以返回DoubleBinding并将label绑定到它,然后它可以工作!

Label label = new Label();

DoubleBinding myFunction(Line[] lines){

      DoubleProperty line_StartX[] = new DoubleProperty[lines.length];
      DoubleProperty line_EndX[] = new DoubleProperty[lines.length];
      DoubleProperty line_StartY[] = new DoubleProperty[lines.length];
      DoubleProperty line_EndY[] = new DoubleProperty[lines.length];

      for (int i = 0; i < lines.length; i++) {
          line_StartX[i] = lines[i].startXProperty();
          line_EndX[i] = lines[i].endXProperty();
          line_StartY[i] = lines[i].startYProperty();
          line_EndY[i] = lines[i].endYProperty();
      }

      DoubleBinding distBinding = new DoubleBinding() {
        {
            for (int i=0; i<3; i++){
                  super.bind(line_StartX[i]);
                  super.bind(line_EndX[i]);
                  super.bind(line_StartY[i]);
                  super.bind(line_EndY[i]);
            }
        }

        @Override
        protected double computeValue() {
            double a = Math.sqrt(Math.pow(lines_StartX[0].getValue() - lines_StartX[1].getValue(),2));
            return a;
        }
      };

      return distBinding;
}

label.textProperty().bind(myFunction(lines).asString());         

它现在按预期行事!最后一个问题,当使用super.bind(prop1, prop2, prop3)时,是否有更简单的方法可以同时在数组中添加整组元素?

© www.soinside.com 2019 - 2024. All rights reserved.