Search code examples
imageviewjavafx-2scaling

Resizing images to fit the parent node


How do I get an image in an ImageView to automatically resize such that it always fits the parent node?

Here is a small code example:

@Override
public void start(Stage stage) throws Exception {
    BorderPane pane = new BorderPane();
    ImageView img = new ImageView("http://...");

    //didn't work for me:
    //img.fitWidthProperty().bind(new SimpleDoubleProperty(stage.getWidth())); 

    pane.setCenter(img);

    Scene scene = new Scene(pane);
    stage.setScene(scene);
    stage.show();
}

Solution

  • @Override
    public void start(Stage stage) throws Exception {
        BorderPane pane = new BorderPane();
        ImageView img = new ImageView("http://...");
    
        img.fitWidthProperty().bind(stage.widthProperty()); 
    
        pane.setCenter(img);
    
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        stage.show();
    }