javafx - 将 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());
而且这种方法行不通。我正在寻找解决此问题的方法。谢谢!
解决方案
更新:已解决
感谢评论中提供的答案,我将函数更改为返回 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)
,有没有更简单的方法可以一次在数组中添加一大堆元素?
推荐阅读
- java - Java,尝试根据命令长度创建特定的网络字节头
- intellij-idea - IntelliJ IDEA 快捷键切换2个字
- python - 当我使用 .append 时,MongoDB 每次第二次插入 null
- python - 无法正确下载嵌套表[编辑]
- python - 舍入Series中的值时出现decimal.InvalidOperation错误
- perl - 我使用 LWP::UserAgent 使用 cookie 有什么问题?
- c# - 可编辑组合框无上下文菜单
- regex - 忽略 Powershell RegEx 上的换行符
- vba - 文件重命名期间的 vba 运行时错误 75
- c# - 如何使用 web api 保存图片?