如何平滑拖动JavaFX多边形? [英] How to smooth drag a JavaFX polygon?

查看:450
本文介绍了如何平滑拖动JavaFX多边形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多边形(三角形)。我想用鼠标拖动它。下面是我尝试的代码,但是使用此代码我无法顺利拖动它。请让我知道如何使其顺利拖动。

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

        }
    });
  } 


推荐答案

问题在于坐标鼠标事件(event.getX()和event.getY())是相对于多边形的;而多边形的layoutX和layoutY是相对于多边形的父级(即窗格)。

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).

有很多方法可以做到这一点,但都涉及到测量事件的坐标相对于固定的东西(例如,场景),并通过这些坐标的变化递增layoutX和layoutY。

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.

这样的事情会起作用:

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

这篇关于如何平滑拖动JavaFX多边形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆