Question

I have a draggable pane which is inside another pane. I want to make the child pane be draggable only inside the boundary of the parent pane but by default, the child pane can be dragged anywhere. How to solve this problem.

Was it helpful?

Solution

Look at this demo. The application produces draggable labels which can be moved all around the scene. To set the boundary limit the following technique is used: inside the onMouseDragged handler we compute the current position of the node and if it does not satisfy some condition we don't modify it. Particularly:

label.setOnMouseDragged(new EventHandler<MouseEvent>() {
    @Override public void handle(MouseEvent mouseEvent) {

      //Sets the drag boundaries limit
      double newX = mouseEvent.getSceneX() + dragDelta.x;
      if (newX > 200 || newX < 10) {
        return;
      }

      label.setLayoutX(mouseEvent.getSceneX() + dragDelta.x);
      label.setLayoutY(mouseEvent.getSceneY() + dragDelta.y);
    }
  });

OTHER TIPS

Adding to xuesheng answer, instead of

 if (newX > 200 || newX < 10) { return; }

use

if( outSideParentBounds(label.getLayoutBounds(), newX, newY) ) {    return; }

Where outSideParentBounds is defined by:

private boolean outSideParentBounds( Bounds childBounds, double newX, double newY) {

        Bounds parentBounds = getLayoutBounds();

        //check if too left
        if( parentBounds.getMaxX() <= (newX + childBounds.getMaxX()) ) {
            return true ;
        }

        //check if too right
        if( parentBounds.getMinX() >= (newX + childBounds.getMinX()) ) {
            return true ;
        }

        //check if too down
        if( parentBounds.getMaxY() <= (newY + childBounds.getMaxY()) ) {
            return true ;
        }

        //check if too up
        if( parentBounds.getMinY() >= (newY + childBounds.getMinY()) ) {
            return true ;
        }

        return false;

        /* Alternative implementation 
        Point2D topLeft = new Point2D(newX + childBounds.getMinX(), newY + childBounds.getMinY());
        Point2D topRight = new Point2D(newX + childBounds.getMaxX(), newY + childBounds.getMinY());
        Point2D bottomLeft = new Point2D(newX + childBounds.getMinX(), newY + childBounds.getMaxY());
        Point2D bottomRight = new Point2D(newX + childBounds.getMaxX(), newY + childBounds.getMaxY());
        Bounds newBounds = BoundsUtils.createBoundingBox(topLeft, topRight, bottomLeft, bottomRight);

        return ! parentBounds.contains(newBounds);
         */
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top