首页 > 解决方案 > 将 JavaFx 标签绑定到根据三个节点属性更改的函数输出

问题描述

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

这是我的尝试:

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());

而且这种方法行不通。我正在寻找解决此问题的方法。谢谢!

标签: javafxjavafx-8

解决方案


更新:已解决

感谢评论中提供的答案,我将函数更改为返回 aDoubleBinding并将其绑定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),有没有更简单的方法可以一次在数组中添加一大堆元素?


推荐阅读