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