JavaFX2:拖动事件的开始和结束坐标

时间:2013-10-02 18:30:08

标签: javafx-2 mouseevent drag

我有一个显示图像的节点(ImageView)和另一个位于其上的节点(矩形)。我需要的行为是当鼠标在矩形上拖动(按下拖动释放手势)时,两个节点应该连贯地移动。我的思维过程朝着以下方向发展:

•在拖动方向上将两个节点移动相同的距离。

对于此选项(可能有更多选项)我需要鼠标拖动的开始和结束之间的距离。我尝试捕获拖动的开始和结束坐标但是没有成功。我想我迷失了哪些处理程序来实现。

我的代码如下:

import javafx.event.EventHandler;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class MyView
{

    double    mouseDragStartX;
    double    mouseDragEndX;

    double    mouseDragStartY;
    double    mouseDragEndY;

    ImageView imageView;

    public MyView()
    {
        imageView = new ImageView("C:\\temp\\test.png");
    }

    private void setRectangleEvents(final MyObject myObject)
    {
        myObject.getRectangle().setOnMousePressed(new EventHandler<MouseEvent>()
        {
            @Override
            public void handle(MouseEvent mouseEvent)
            {
                mouseDragStartX = mouseEvent.getX();
                mouseDragStartY = mouseEvent.getY();
                mouseEvent.consume();
            }
        });

        myObject.getRectangle().setOnMouseReleased(new EventHandler<MouseEvent>()
        {
            public void handle(MouseEvent mouseEvent)
            {
                mouseDragEndX = mouseEvent.getX();
                mouseDragEndY = mouseEvent.getY();
                myObjectDraggedHandler();
            }
        });
    }

    private void myObjectDraggedHandler()
    {

    Rectangle2D viewport = this.imageView.getViewport();
    double newX = this.imageView.getImage().getWidth()
        + (mouseDragEndX - mouseDragStartX);
    double newY = this.imageView.getImage().getHeight()
        + (mouseDragEndY - mouseDragStartY);

        this.imageView.setViewport(new Rectangle2D(newX, newY, viewport.getWidth(),     viewport
            .getHeight()));

    }
}

P.S:此代码仅用于指示我要实现的内容,并且无法正确编译。

或许我的问题应该是: 如何捕捉鼠标拖动的长度或跨度?

1 个答案:

答案 0 :(得分:2)

尝试这个我认为它会帮助你

obj.setOnMousePressed(new EventHandler<MouseEvent>() {
  @Override public void handle(MouseEvent mouseEvent) {
    // record a delta distance for the drag and drop operation.
    dragDelta.x = stage.getX() - mouseEvent.getScreenX();
    dragDelta.y = stage.getY() - mouseEvent.getScreenY();
  }
});
obj.setOnMouseDragged(new EventHandler<MouseEvent>() {
  @Override public void handle(MouseEvent mouseEvent) {
      stage.setX(mouseEvent.getScreenX() + dragDelta.x);
    stage.setY(mouseEvent.getScreenY() + dragDelta.y);
  }
});