Search code examples
imageviewjavafx-2

JavaFX ImageView resize in StackPane


I have a ploblem with resizing of ImageView in StackPane: If StackPane is root container and I bind image's height and width to StackPane, everything is fine.

<StackPane id="StackPane" fx:id="stack" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: lightgreen;" styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml" fx:controller="javafxapplication8.FXMLController">
  <children>
    <ImageView fx:id="image" fitHeight="100.0" fitWidth="300.0" pickOnBounds="true" preserveRatio="true" />
  </children>
  <stylesheets>
    <URL value="@fxml.css" />
  </stylesheets>
</StackPane>

But if I place such stack pane in, for example, grid, than image doesnt resize properly. As I read, the problem that ImageView is non-Resizable. Is there any ways to make it resizable? Or could you give some advise how to resize ImageView?


Solution

  • It sounds like you are trying to create a background image for the StackPane. In which case applying the image via CSS may be a better route to use than an ImageView.

    .stack-pane {
      -fx-background-image: url("flower.png");
      -fx-background-size: cover;
    }
    

    See the background images section of the Region specification in the JavaFX CSS reference guide.

    Making ImageView itself resizable is an unresolved major issue. The issue links to code for a simple workaround - a resizable ImagePane wrapping an Image to fill the resizable pane.