gpt4 book ai didi

java - 我需要帮助将文本绑定(bind)到位于两个圆之间的线,然后每次移动圆时更新线的距离

转载 作者:行者123 更新时间:2023-11-30 07:31:27 24 4
gpt4 key购买 nike

我有 2 个圆圈,其中 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));

关于java - 我需要帮助将文本绑定(bind)到位于两个圆之间的线,然后每次移动圆时更新线的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36062973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com