我有一个可拖动的窗格,位于另一个窗格中。我想让子窗格只能在父窗格的边界内拖动,但默认情况下,子窗格可以拖动到任何位置。如何解决这个问题。
答案 0 :(得分: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);
}
});
答案 1 :(得分: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);
*/
}