How to smooth drag a JavaFX polygon?

2019-05-10 14:25发布

I have a polygon (triangle shape). I want to make it draggable with mouse. Below is the code that I tried, but with this code I am not able to drag it smoothly. Please let me know how can I achieved to make it draggable smoothly.

    public void start(Stage primaryStage) throws Exception {
    AnchorPane pane = new AnchorPane();

    final Polygon polygon   = new Polygon();
    polygon.getPoints().addAll(new Double[]{
            50.0,  50.0,
            30.0, 70.0,
            70.0, 70.0 });

    pane.getChildren().add(polygon);

    Scene scene = new Scene(pane, 200, 200, Color.WHITE);
    primaryStage.setScene(scene);
    primaryStage.show();

    polygon.setOnMouseDragged(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            polygon.setLayoutX(event.getX());
            polygon.setLayoutY(event.getY());

        }
    });
  } 

1条回答
等我变得足够好
2楼-- · 2019-05-10 14:59

The problem is that the coordinates of the mouse event (event.getX() and event.getY()) are relative to the polygon; whereas the layoutX and layoutY of the polygon are relative to the parent of the polygon (i.e. the pane).

There are lots of ways to do this, but all involve measuring the coordinates of the event relative to something fixed (the Scene, for example) and incrementing the layoutX and layoutY by the change in those coordinates.

Something like this will work:

    final ObjectProperty<Point2D> mousePosition = new SimpleObjectProperty<>();

    polygon.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
        }
    });

    polygon.setOnMouseDragged(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            double deltaX = event.getSceneX() - mousePosition.get().getX();
            double deltaY = event.getSceneY() - mousePosition.get().getY();
            polygon.setLayoutX(polygon.getLayoutX()+deltaX);
            polygon.setLayoutY(polygon.getLayoutY()+deltaY);
            mousePosition.set(new Point2D(event.getSceneX(), event.getSceneY()));
        }
    });
查看更多
登录 后发表回答