*15.16(两个可移动的顶点以及它们间的距离)
- 请编写一个程序,显示两个分别位于(40,40)和(120,150) 的半径为10的圆,并用一条直线连接两个圆,如图15-28b所示。圆之间的距离显示在直线上。 用户可以拖动圆,圆和它上面的直线会相应移动,并且两个圆之间的距离会更新
答题思路:
- 新建一个Pane()面板, 先新建一条直线,再新建两个圆(这是因为直线直接连接圆的中心 点,再把圆填充为白色,如果想从外围连接圆请参考编程练习题14.22)
- 定义一个distance方法用于计算距离
- 用一个Text用于表示距离
- 为circle1注册一个鼠标事件(鼠标拖动:setOnMouseDragged()),将cirlce1的位置设为鼠标的位置,并将Line的开始点设为鼠标位置,同时更新Text的内容和位置
- 为circle2注册一个鼠标事件,与第4步差不多,更新Line的结束点和cirlce2
示例代码:编程练习题15_16TwoMovablePoints.java
package chapter_15;import javafx.application.Application;
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 编程练习题15_16TwoMovablePoints extends Application{@Overridepublic void start(Stage primaryStage) throws Exception {Pane pane = new Pane();Line line = new Line(40, 40, 120, 150);Circle c1 = new Circle(40, 40, 10);Circle c2 = new Circle(120, 150, 10);c1.setFill(Color.WHITE);c2.setFill(Color.WHITE);c1.setStroke(Color.BLACK);c2.setStroke(Color.BLACK);Text distanceText = new Text(distance(line.getEndX(), line.getStartX(), line.getEndY(), line.getStartY())+"");distanceText.setX(Math.abs(line.getEndX()-line.getStartX()));distanceText.setY(Math.abs(line.getEndY()-line.getStartY()));pane.getChildren().addAll(line,c1,c2,distanceText);c1.setOnMouseDragged(e ->{double x = e.getX();double y = e.getY();c1.setCenterX(x);c1.setCenterY(y);line.setStartX(x);line.setStartY(y);double textX = (line.getStartX() + line.getEndX()) / 2;double textY = (line.getStartY() + line.getEndY()) / 2;distanceText.setX(textX);distanceText.setY(textY);distanceText.setText(distance(line.getEndX(), x, line.getEndY(), y)+"");});c2.setOnMouseDragged(e ->{double x = e.getX();double y = e.getY();c2.setCenterX(x);c2.setCenterY(y);line.setEndX(x);line.setEndY(y);distanceText.setText(distance(x, line.getStartX(), y, line.getStartY())+"");double textX = (line.getStartX() + line.getEndX()) / 2;double textY = (line.getStartY() + line.getEndY()) / 2;distanceText.setX(textX);distanceText.setY(textY);});Scene scene = new Scene(pane, 300, 300);primaryStage.setTitle("编程练习题15_16TwoMovablePoints");primaryStage.setScene(scene);primaryStage.show();}public static void main(String[] args) {Application.launch(args);}public double distance(double x2,double x1, double y2, double y1) {return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));}
}
- 代码结果