【发布时间】:2015-02-17 17:01:25
【问题描述】:
如何在 JavaFX 中对形状(例如圆圈)进行分组以拖动它们?示例代码基于 Oracle 教程。每个单独的圆圈都可以移动。拖动时我想单独移动蓝色圆圈。我想在单击并拖动绿色圆圈时移动绿色和蓝色圆圈,并在单击并拖动红色圆圈时移动它们三个。有什么想法吗?
public class DragGroupSample extends Application {
public static void main( String[] args ) {
launch();
}
private void makeDraggable( Circle circle ) {
DragContext dragContext = new DragContext();
// --- remember initial coordinates of mouse cursor and node
circle.addEventFilter( MouseEvent.MOUSE_PRESSED, (
final MouseEvent mouseEvent ) -> {
dragContext.dx = mouseEvent.getX() - circle.getCenterX();
dragContext.dy = mouseEvent.getY() - circle.getCenterY();
} );
// --- Shift node calculated from mouse cursor movement
circle.addEventFilter( MouseEvent.MOUSE_DRAGGED, (
final MouseEvent mouseEvent ) -> {
circle.setCenterX( mouseEvent.getX() + dragContext.dx );
circle.setCenterY( mouseEvent.getY() + dragContext.dy );
} );
// --- Drop card onto allowed target field
circle.addEventFilter( MouseEvent.MOUSE_RELEASED, (
final MouseEvent mouseEvent ) -> {
circle.setCenterX( mouseEvent.getX() + dragContext.dx );
circle.setCenterY( mouseEvent.getY() + dragContext.dy );
} );
}
@Override
public void start( Stage primaryStage ) throws Exception {
Circle[] circles = new Circle[3];
circles[0] = new Circle( 30.0, 30.0, 30.0, Color.RED );
circles[1] = new Circle( 45.0, 45.0, 30.0, Color.GREEN );
circles[2] = new Circle( 60.0, 60.0, 30.0, Color.BLUE );
for ( Circle circle : circles ) {
makeDraggable( circle );
}
Group root = new Group();
root.getChildren().addAll( circles[0], circles[1], circles[2] );
primaryStage.setResizable( false );
primaryStage.setScene( new Scene( root, 400, 350 ) );
primaryStage.setTitle( DragGroupSample.class.getSimpleName() );
primaryStage.show();
}
private static final class DragContext {
public double dx, dy;
}
}
【问题讨论】:
-
James_D 所说的。或者您也可以在这里查看:stackoverflow.com/questions/28300067/…,这与您的需求相似。