JavaFX resize ImageView in center of BorderPane

62 views Asked by At

I have a ImageView in the center of a BorderPane. Left and right are two buttons. The BorderPnae is inside a splitpane. I bind the size of the ImageView to the BorderPane like so:

imageView.fitHeightProperty().bind(borderPane.heightProperty());
imageView.fitWidthProperty().bind(borderPane.widthProperty());
imageView.setManaged(false);

It rezise but the image is not in the center when setManaged is false. If I remove this lines, the image is nice in the center. Here is a mwe:

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {

            SplitPane root = new SplitPane();
            BorderPane borderPane = new BorderPane();
            ImageView imageView = new ImageView();
            VBox placeHolder = new VBox();
            
            imageView.fitHeightProperty().bind(borderPane.heightProperty());
            imageView.fitWidthProperty().bind(borderPane.widthProperty());
            imageView.setManaged(false);
            
            borderPane.setCenter(imageView);
            imageView.setImage(new Image("pathToImage"));
            root.getItems().addAll(borderPane,placeHolder);
            Scene scene = new Scene(root,700,700);          
            primaryStage.setScene(scene);
            
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

enter image description here

Im looking for a way to archive both. I tried with an Hbox as a container for the buttons and the imageview but that also disables the sizing.

1

There are 1 answers

2
Slaw On BEST ANSWER

If you are trying to create a "resizable image view" then see the ImageViewPane class from this answer by jewelsea.

However, your current code seems more like trying to set a background image. You have:

imageView.fitHeightProperty().bind(borderPane.heightProperty());
imageView.fitWidthProperty().bind(borderPane.widthProperty())

This will cause the image to be the size of the entire BorderPane, not just its "center". In other words, the image is functioning like a background image. Your screenshot would seem to agree with this (the image in your app looks very background-esque). If you want a background image, then you should set the background of the BorderPane instead of using an ImageView.

In code:

BackgroundImage bgImage =
    new BackgroundImage(
        new Image("..."),
        BackgroundRepeat.NO_REPEAT,
        BackgroundRepeat.NO_REPEAT,
        BackgroundPosition.CENTER,
        new BackgroundSize(1, 1, true, true, false, false));
borderPane.setBackground(new Background(bgImage));

In CSS:

#theBorderPaneId {
    -fx-background-image: url(...);
    -fx-background-repeat: no-repeat;
    -fx-background-position: center;
    -fx-background-size: stretch;
}