JavaFX2: Drag Event start and end coordinates

Posted by user on Stack Overflow See other posts from Stack Overflow or by user
Published on 2013-10-02T18:30:07Z Indexed on 2013/11/01 9:55 UTC
Read the original article Hit count: 172

Filed under:
|
|

I have one node(ImageView) that displays an image and another node(rectangle) that resides on top of it. The behavior I need is that when the mouse is dragged(press-drag-release gesture) over the rectangle, both the nodes should move coherently. My thought process goes in the following direction:

• Move both the nodes by the same distance in the direction of the drag.

For this option(maybe there are more options) I need the distance between the start and end of the mouse drags. I tried capturing the start and end coordinates of the drag but have been unsuccessful. I think I am getting lost in which handlers to implement.

The code I have is below:

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: This code is just for indicating what I am trying to implement and will not compile correctly.

Or maybe my question should just have been: How to capture the length or span of a mouse drag?

© Stack Overflow or respective owner

Related posts about javafx-2

Related posts about mouseevent