4

我有一个显示图像的节点(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()));

    }
}

PS:此代码仅用于指示我正在尝试实现的内容,并且无法正确编译。

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

4

1 回答 1

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);
  }
});
于 2013-11-01T09:51:33.610 回答