2014-03-27 58 views

回答

1

看看這個demo。該應用程序生成可在整個場景中移動的可拖動標籤。要設置邊界限制,使用以下技術:在onMouseDragged處理程序中,我們計算節點的當前位置,如果它不滿足某些條件,我們不會修改它。特別是:

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

真的謝謝你這對我的作品。但是這個代碼中的一個問題是,如果我們保留「if」語句,它會使窗格比刪除它慢得多。如果能解決這個問題,我會很高興。 謝謝 – viper

+0

我認爲這是一個部分的答案。它回答「我如何限制」,但忽略「在父窗格邊界內」 – c0der

+0

嗯,而不是硬編碼的值,你可以使用屬性,這取決於邊界窗格的邊界。 – xuesheng

0

添加到xuesheng answer,而不是

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

使用

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

outSideParentBounds被定義爲:

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