【问题标题】:How to change size of ImageView when changing size of window in javafx guijavafx gui中更改窗口大小时如何更改ImageView的大小
【发布时间】:2019-08-09 00:31:24
【问题描述】:
我以前没有使用过多的 gui,但我正在尝试通过使用 SceneBuilder 构建 javafx 应用程序来学习它。现在,当我调整窗口大小时,我无法让 ImageView 调整大小。
我正在使用 gridPane,并且我已将 ImageView 放置在 gridPane 中的一条路线内的 anchorPane 上。当我在运行应用程序时更改窗口大小时,gridPane 正在更改大小,但 ImageView 不会更改大小。当我在运行应用程序时更改窗口大小时,我希望 Imageview 相应地更改大小。
已经尝试在论坛上阅读类似的问题,但没有找到我可以使用的解决方案,有没有人有好的方法来做到这一点?
非常感谢所有答案。
【问题讨论】:
标签:
user-interface
imageview
javafx-8
scenebuilder
【解决方案1】:
为了简单起见,您可以使用绑定,这里是完整的示例代码
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);
}
}