**15.18(使用鼠标来移动一个矩形)
- 请编写一个程序显示一个矩形。可以使用鼠标单击矩形内部并且拖动(即按住鼠标移动)矩形到鼠标的位置。鼠标点成为矩形的中央
- 习题思路:
-
新建一个面板Pane(),新建一个Rectangle()
-
为Rectangle注册一个事件(鼠标拖动:setOnMouseDragged())
-
设置Rectangle的xy为当前鼠标位置的(mouseX-Rw/2.0),(mouseY-Rh/2.0),Rw为矩形的宽,Rh为矩形的高。因为矩形本身的xy坐标是从左上角开始的,所以要减去宽与高的一半。
代码示例:编程练习题15_18UseMouseMoveRectangle.java
package chapter_15;import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;public class 编程练习题15_18UseMouseMoveRectangle extends Application{@Overridepublic void start(Stage primaryStage) throws Exception {Pane pane = new Pane();Rectangle rectangle = new Rectangle(120, 130, 60, 40);pane.getChildren().add(rectangle);rectangle.setOnMouseDragged(e ->{double mouseX = e.getX();double mouseY = e.getY();double rw = rectangle.getWidth();double rh = rectangle.getHeight();double x = mouseX-rw/2.0;double y = mouseY-rh/2.0;rectangle.setX(x);rectangle.setY(y);});Scene scene = new Scene(pane, 300, 300);primaryStage.setTitle("编程练习题15_18UseMouseMoveRectangle");primaryStage.setScene(scene);primaryStage.show();}public static void main(String[] args) {Application.launch(args);}
}
- 结果展示