JavaFX - 根据加载的图像大小调整窗口大小

[英]JavaFX - Resize Window based on loaded image size

My main Windows appearance is defined by an FXML file with a BorderPane structure. The center tag is defined as follows:


    <ScrollPane focusTraversable="false">
            <Pane fx:id="mapArea">
                <ImageView fx:id="mapImageView" />

In the program, the user can open an image file representing a map, add some points of interests, and save it all for later. The image can be of any size. What I want is for the main window to resize so that when an image is loaded, it fits perfectly in the ImageView, although users are allowed to resize manually, for example if the image is too large for their monitor.


Right now in my controller, I execute the following lines when an image is loaded:


double width = getMap().getImage().getWidth();
double height = getMap().getImage().getHeight();

This has some strange (to me) effects. The height of the window is set so that the image COULD be fully shown if the ImageView was the only Node in the Scene, but obviously it is not. The width of the windows doesn't seem to be affected at all.


I have tried fiddling around with different properties on different objects, minWidth, maxWidth, prefWidth, setResizeable and so on, but I feel like I am stumbling in the dark. I don't really know how it all comes together, and this SOUNDS like something that should be trivial.


Please let me know if you require more code.


1 个解决方案


In JavaFX when you want to set a value to some field X it will typically have a corresponding setX() method.


prefWidth(double) and prefHeight(double) return node's preferred values for width and height.


If you want to set the window(JavaFX Stage) size then in your start(Stage) method, obtain a reference to the primaryStage. Once you've loaded your image, you can do stage.setWidth(width) and stage.setHeight(height) Example:

如果要在start(Stage)方法中设置窗口(JavaFX Stage)大小,请获取对primaryStage的引用。加载图像后,可以执行stage.setWidth(width)和stage.setHeight(height)示例:

public class YourJavaFXApp extends Application {

    private Stage stage;

    public void start(Stage primaryStage) throws Exception {
        stage = primaryStage;
        // some code here

If you want to resize the loaded image to fit the current window size instead then you can use mapImageView.setFitWidth(width) and mapImageView.setFitHeight(height)





粤ICP备14056181号  © 2014-2020