如何在javafx gui中更改窗口大小时更改ImageView的大小

问题描述 投票:0回答:1

我之前没有和gui一起工作,但是我试图通过使用SceneBuilder构建一个javafx应用程序来学习它。现在,当我调整窗口大小时,我无法调整ImageView的大小。

我正在使用gridPane,我已经在gridPane中的一个路由中的anchorPane上放置了一个ImageView。当我运行应用程序时更改窗口大小时gridPane正在改变大小,但ImageView不会改变大小。我希望Imageview在我运行应用程序时更改窗口大小时相应地更改大小。

我试图在论坛上阅读类似的问题,但没有找到我可以使用的解决方案,有没有人有一个很好的方法来做到这一点?

真的很感激所有的答案。

user-interface imageview javafx-8 scenebuilder
1个回答
2
投票

您可以使用绑定来简化,这里是完整的示例代码

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage){
        GridPane gridPane = new GridPane();
        AnchorPane anchorPane = new AnchorPane();

        // Set image with url
        Image image = new Image("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR-524e2cCaY9TUn8vglN3nqqOlT0jIJIIty-Z81S49q9Np6Yws");
        ImageView imageView = new ImageView(image);

        // Bind the imageView width property to gridPane width property
        // So, if width of gridPane change, the width of imageView automatically will be change
        imageView.fitWidthProperty().bind(gridPane.widthProperty());

        // Make the ratio same with original image
        imageView.setPreserveRatio(true);

        anchorPane.getChildren().add(imageView);
        gridPane.getChildren().add(anchorPane);
        Scene scene = new Scene(gridPane, 600, 400);
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Fullscreen

Not fullscreen

© www.soinside.com 2019 - 2024. All rights reserved.