Java 我需要帮助将文本绑定到两个圆之间的线,然后在每次移动圆时更新线的距离

Java 我需要帮助将文本绑定到两个圆之间的线,然后在每次移动圆时更新线的距离,java,javafx,Java,Javafx,我有两个圆圈,其中一条线固定在x和y上。通过拖动可以移动圆圈,线也会随之移动。我不知道如何定位文本,使其位于直线的中心,并在移动圆时移动。我也不知道如何在每次移动时将文本更新到两个圆圈之间的距离 import javafx.beans.value.ObservableValue; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.Pane; import javafx.

我有两个圆圈,其中一条线固定在x和y上。通过拖动可以移动圆圈,线也会随之移动。我不知道如何定位文本,使其位于直线的中心,并在移动圆时移动。我也不知道如何在每次移动时将文本更新到两个圆圈之间的距离

import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class CircleWithStirngApp extends Application {
   @Override
   public void start(Stage primaryStage) throws Exception {
        Circle circle1 = new Circle(40,40,10);
        Circle circle2 = new Circle(120,150,10);
        Line line = new Line();
        Text text = new Text(60,60,"");

        line.startXProperty().bind(circle1.centerXProperty());
        line.startYProperty().bind(circle1.centerYProperty());
        line.endXProperty().bind(circle2.centerXProperty());
        line.endYProperty().bind(circle2.centerYProperty());

        Pane pane = new Pane();
        pane.getChildren().add(circle1);
        pane.getChildren().add(circle2);
        pane.getChildren().add(line);
        pane.getChildren().add(text);

        circle1.setOnMouseDragged(e ->{
            circle1.setCenterX(e.getX());
            circle1.setCenterY(e.getY());
        });
        circle2.setOnMouseDragged(e ->{
            circle2.setCenterX(e.getX());
            circle2.setCenterY(e.getY());
        });

        Scene scene = new Scene(pane,200,200);
        primaryStage.setTitle("Circle With String");
        primaryStage.setScene(scene);
        primaryStage.show();

    }
}
只用

DoubleBinding distance = Bindings.createDoubleBinding(() -> {
    Point2D start = new Point2D(circle1.getCenterX(), circle1.getCenterY());
    Point2D end = new Point2D(circle2.getCenterX(), circle2.getCenterY());
    return start.distance(end);
}, circle1.centerXProperty(), circle1.centerYProperty(), 
   circle2.centerXProperty(), circle2.centerYProperty());
然后你可以做像这样的事情

text.textProperty().bind(distance.asString("Distance: %f"));
对于居中文本,可以使用

text.xProperty().bind(circle1.centerXProperty().add(circle2.centerXProperty()).divide(2));
text.yProperty().bind(circle1.centerYProperty().add(circle2.centerYProperty()).divide(2));

感谢@fabian的编辑。感谢@James_D的帮助。感谢@fabian的帮助。这是一个很好的例子。