Java黑皮书15.16(两个可移动的顶点以及它们之间的距离)
package sample;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
Circle circle1 = new Circle(200, 300, 5);
Circle circle2 = new Circle(400, 300, 5);
circle1.setFill(Color.WHITE);
circle2.setFill(Color.WHITE);
circle1.setStroke(Color.BLACK);
circle2.setStroke(Color.BLACK);
Line line = new Line(circle1.getCenterX(), circle1.getCenterY(), circle2.getCenterX(), circle2.getCenterY());
double distance = new Point2D(circle1.getCenterX(), circle1.getCenterY()).distance(circle2.getCenterX(), circle2.getCenterY());
Text text = new Text((circle1.getCenterX() + circle2.getCenterX()) / 2, (circle1.getCenterY() + circle2.getCenterY()) / 2, (int) distance + "");
pane.getChildren().addAll(line, circle1, circle2, text);
circle1.setOnMouseDragged(e -> {
circle1.setCenterX(e.getX());
circle1.setCenterY(e.getY());
line.setStartX(e.getX());
line.setStartY(e.getY());
double distance_now = new Point2D(circle1.getCenterX(), circle1.getCenterY()).distance(circle2.getCenterX(), circle2.getCenterY());
text.setX((circle1.getCenterX() + circle2.getCenterX()) / 2);
text.setY((circle1.getCenterY() + circle2.getCenterY()) / 2);
text.setText((int) distance_now + "");
});
circle2.setOnMouseDragged(e -> {
circle2.setCenterX(e.getX());
circle2.setCenterY(e.getY());
line.setEndX(e.getX());
line.setEndY(e.getY());
double distance_now = new Point2D(circle1.getCenterX(), circle1.getCenterY()).distance(circle2.getCenterX(), circle2.getCenterY());
text.setX((circle1.getCenterX() + circle2.getCenterX()) / 2);
text.setY((circle1.getCenterY() + circle2.getCenterY()) / 2);
text.setText((int) distance_now + "");
});
Scene scene = new Scene(pane, 600, 600);
primaryStage.setTitle("两个可移动的顶点以及它们之间的距离");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8b8f5042e27d1833906354efa0fd50fb.png)