将JavaFx标签绑定到函数输出,该函数输出会根据三个节点属性进行更改
我想让Label textProperty绑定到函数中的一个值,该函数将接受一个节点数组(即三行节点),然后根据节点的position属性(即startXProperty)进行一些计算,这样每当节点的位置发生更改时,标签文本都会相应地更新 这是我的尝试:将JavaFx标签绑定到函数输出,该函数输出会根据三个节点属性进行更改,javafx,javafx-8,Javafx,Javafx 8,我想让Label textProperty绑定到函数中的一个值,该函数将接受一个节点数组(即三行节点),然后根据节点的position属性(即startXProperty)进行一些计算,这样每当节点的位置发生更改时,标签文本都会相应地更新 这是我的尝试: Label label = new Label(); DoubleProperty myFunction(Line[] lines){ DoubleProperty property= new SimpleDoublePrope
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());
这种方法不起作用。我正在想办法解决这个问题。谢谢 更新:已解决 感谢评论中提供的答案,我更改了函数以返回
双重绑定
,并将标签
绑定到它,然后它就工作了
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());
Label Label=新标签();
DoubleBinding myFunction(第[]行){
DoubleProperty line_StartX[]=新的DoubleProperty[lines.length];
DoubleProperty line_EndX[]=新的DoubleProperty[lines.length];
DoubleProperty line_StartY[]=新的DoubleProperty[lines.length];
DoubleProperty line_EndY[]=新的DoubleProperty[lines.length];
对于(int i=0;i 对于(int i=0;i您需要一个绑定(它侦听它所依赖的属性/可观察值)请参阅:另请参阅。@kleopatra:谢谢!我更新了修改后的代码段。请告诉我哪里有更好的选择。谢谢!@Slaw:谢谢提供帮助函数!我搜索了一点,看起来很方便快速绑定!如果您使用的是javafx.scene.shape.Line
,为什么不直接使用正确的直接连接那些行
s?此外,您似乎没有声明行_StartX
和行_EndX
(或相应的Y
)字段正确的左边表示字段是数组,但右边没有声明数组。@Slaw:很好,谢谢!右边也应该是数组。更正!我之所以使用数组而不是直接从属性检索,是因为在我的实际实现中,这些行具有不同的优先级,它在函数中的某个位置指定,因此[0]每个数组中的位置将根据所选的行而不断变化。假设我正确理解了您的要求,我不相信您的代码会按照您的要求工作。当您交换行
中的元素时,它不会影响各种DoubleProperty
数组。除非需要,否则也可以使用行\u startX[0]-线路_StartX[1]
无效。它试图从DoubleProperty
中减去DoubleProperty
。我怀疑您是想减去这些属性的值?另外,当行移动时绑定是否应该无效?oho以前没有注意到:请学习java命名约定并坚持它们:-)