How do I center an Image view in an anchor pane?

前端 未结 3 767
天涯浪人
天涯浪人 2021-01-19 04:20

I am using scene builder to create my GUI and I am displaying Images as users select items in a list. The Images are of different sizes and when an

3条回答
  •  臣服心动
    2021-01-19 04:53

    Create a Group and scene in your start method:

    Group root = new Group();
    Scene scene = new Scene(root, 551, 400, Color.BLACK);
    primaryStage.setScene(scene);
    

    Create an ImageView and set the following properties:

    ImageView imageView = new ImageView();
    // set aspect ratio
    imageView.setPreserveRatio(true);
    // resize based on the scene
    imageView.fitWidthProperty().bind(scene.widthProperty());
    imageView.fitHeightProperty().bind(scene.heightProperty());
    

    Create a StackPane (at least that is what I used) and bind your properties:

    StackPane stack = new StackPane();
    stack.getChildren().add(imageView);
    
        stack.translateXProperty()
                .bind(scene.widthProperty().subtract(stack.widthProperty())
                        .divide(2));
    
        stack.translateYProperty()
                .bind(scene.heightProperty().subtract(stack.heightProperty())
                        .divide(2));
    

    Add this stack to root element:

    root.getChildren().add(stack);
    

    Show primaryStage and execute other code in your start method:

    primaryStage.show();
    

提交回复
热议问题