Warm tip: This article is reproduced from serverfault.com, please click

How can I make responsive ImageView in FXML (JavaFX)

发布于 2020-11-28 18:14:28

I have a scene showing 3 images, and I want each of them to take a third of the width of the scene. From now, I have made 3 Pane of each 30% of it, it works. But in those Pane, I can't make my ImageView use only the width of the Pane.

<GridPane GridPane.rowIndex="1" GridPane.columnIndex="0">
        <ImageView GridPane.columnIndex="0" fx:id="imgChasseur" preserveRatio="true" onMouseClicked="#handleChoixChasseur"/>
        <ImageView GridPane.columnIndex="1" fx:id="imgMage" preserveRatio="true" onMouseClicked="#handleChoixMage"/>
        <ImageView GridPane.columnIndex="2" fx:id="imgGuerrier" preserveRatio="true" onMouseClicked="#handleChoixGuerrier"/>
    <columnConstraints>
        <ColumnConstraints percentWidth="33" />
        <ColumnConstraints percentWidth="33" />
        <ColumnConstraints percentWidth="33" />
    </columnConstraints>
    <rowConstraints>
        <RowConstraints percentHeight="100" />
    </rowConstraints>        
</GridPane>

With that sample of code, I can't see the three because they are huge, and with the 'fitWidth="100"' in the 3 ImageView, they are too small.

The way I understand it is that the 'fitWidth' works in pixels, but it's not a responsive way, so it doesn't help me very much...

The GridPane is the only Pane which seems to have percentage values, so I thought it could help me make them responsive, but it doesn't seem so. Is there a way, regardless of the Pane I should use?

Questioner
QDelage
Viewed
0
QDelage 2020-11-29 22:00:58

I found a solution : I added a listener on the surrounding Pane which modifies the fitWidth of my ImageView's in the Controller

    paneOriginal.widthProperty().addListener((ChangeListener<? super Number>) new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
            imgChasseur.setFitWidth(paneOriginal.getWidth() / 3);
            imgMage.setFitWidth(paneOriginal.getWidth() / 3);
            imgGuerrier.setFitWidth(paneOriginal.getWidth() / 3);
        }
    });

With this, I can resize my scene whenever I want and it still fits (and I have to call those three lines at the loading of the FXML one time at least of course.