문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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);
         */
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top