JavaFX Stage width/height after sizeToScene call

11,576

The stage's width and height values are calculated after the stage has been shown. You can set minimum values of these values after the stage shown:

@Override
public void start(Stage primaryStage) {
    StackPane root = new StackPane();
    Scene scene = new Scene(root, 800, 600);
    primaryStage.setScene(scene);

    System.out.println("before sceneW " + scene.getWidth());
    System.out.println("before sceneH " +  scene.getHeight());
    System.out.println("before stageW " + primaryStage.getWidth());
    System.out.println("before stageH " + primaryStage.getHeight());

    primaryStage.show();

    System.out.println("after sceneW " + scene.getWidth());
    System.out.println("after sceneH " +  scene.getHeight());
    System.out.println("after stageW " + primaryStage.getWidth());
    System.out.println("after stageH " + primaryStage.getHeight());

    primaryStage.setMinWidth(primaryStage.getWidth());
    primaryStage.setMinHeight(primaryStage.getHeight());
}

sizeToScene() is similar to Swing's (AWT) pack(). I think you don't need it here.

Share:
11,576

Related videos on Youtube

Morv
Author by

Morv

Updated on September 15, 2022

Comments

  • Morv
    Morv over 1 year

    I'm currently writing an application that I want to have a minimum scene size of 800x600 pixels. At first attempt I simply used stage.setMinWidth and stage.setMinHeight but these values count for the whole window and not only for the scene, so only 7xx x 5xx of the scene are shown. So I searched the Stage javadoc and found sizeToScene which is exactly what i need, after call the stage size is bigger than 800x600 and the scene is fully shown with it's 800x600 pixels.

    The only problem now is that this method call doesn't save the stage width and height in the stage itself and therefore I can't set the minimum width and height to the current width and height calculated by sizeToScene.

    stage.getWidth and stage.getHeight always return NaN.

    I could hardcode these values now that I got them (made a screenshot and checked in paint.net) but this wouldn't work with other OS/versions of Windows/decorators.

    I'm working on Windows 7, JavaFX 2.2, JDK 7_21.

    Has someone got an idea how to get the width and height after the method call? I hope you understand what my problem is otherwise just tell me. If you need code i can give it to you but i guess you won't need it. Thanks!

  • Morv
    Morv almost 11 years
    Many thanks, i just didn't think of checking the width and height after stage.show()...it's so easy.