我有一个可拖动的窗格,它位于另一个窗格内。我想让子窗格只能在父窗格的边界内拖动,但默认情况下,子窗格可以拖动到任何地方。如何解决这个问题呢。
问问题
2680 次
2 回答
2
看看这个演示。该应用程序生成可在场景中移动的可拖动标签。要设置边界限制,使用以下技术:在 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);
}
});
于 2014-03-29T21:24:07.140 回答
0
添加到xuesheng 答案中,而不是
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);
*/
}
于 2017-07-07T11:00:00.140 回答