Why JavaFX- method .getLayoutBounds().getWidth() returns 0?

537 Views Asked by At

I need to dynamically retrieve the width of the left part of my JavaFX-BorderPane. Here is the code-snippet, but both methods I use always return 0 although left component is laid out at this point of time...

double leftWidth = ((VBox) this.getLeft()).getWidth();

same with:

double leftWidth = ((VBox) this.getLeft()).getLayoutBounds().getWidth();

How to do this properly?

Here a mcve:

public class BorderPaneExample extends Application {

@Override
public void start(Stage primaryStage) {

    Button btn = new Button();
    btn.setText("Left side of BorderPane");
    BorderPane root = new BorderPane();
    root.setLeft(btn);
    Scene scene = new Scene(root, 640, 480);
    primaryStage.setScene(scene);

    primaryStage.show();

    // ... later on retrieve the width of the left side:
    System.out.println(root.getLeft().getLayoutBounds().getWidth());
}

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

There are 1 best solutions below

5
Sergey Grinev On

Most probably you are calling them before stage.show() has happened.

Bounds are not initialized until the window is shown. Move them to be calculated later, or try to wrap them into Platform.runLater() as a workaround.