简体   繁体   中英

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

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);
}}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM