Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to smooth drag a JavaFX polygon?

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());

        }
    });
  } 
like image 443
Angom Avatar asked Mar 21 '23 08:03

Angom


1 Answers

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()));
        }
    });
like image 148
James_D Avatar answered Mar 29 '23 08:03

James_D