1

I am working on an application where I have to display a tree. I started from: Graph Visualisation (like yFiles) in JavaFX . The tree gets displayed, but for ButtonCell calling the method getWidth or any variant of getBoundsInLocal, getBoundsInParent, getLayoutBounds returns 0 and getPrefWidth returns -1.

How do I get the width and height of the button?

Community
  • 1
  • 1
Andrew
  • 165
  • 4
  • 16
  • When are you calling these methods? If you call them before layout is performed (which typically only happens when the UI is actually rendered to the screen), they will give dimensions of zero. (It would probably help to post a [MCVE].) – James_D Mar 22 '16 at 23:39
  • Seems like this could be a duplicate of: [Get the height of a node in JavaFX (generate a layout pass)](http://stackoverflow.com/questions/26152642/get-the-height-of-a-node-in-javafx-generate-a-layout-pass). – jewelsea Mar 23 '16 at 17:37

1 Answers1

5

You have to add the components before the stage is shown and get the values after the stage is shown, i. e.:

public void start(Stage primaryStage) {
    BorderPane root = new BorderPane();

    graph = new Graph();

    addGraphComponents();

    root.setCenter(graph.getScrollPane());

    Scene scene = new Scene(root, 1024, 768);
    scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());

    primaryStage.setScene(scene);
    primaryStage.show();

    Layout layout = new RandomLayout(graph);
    layout.execute();

    for( Cell cell: graph.getModel().getAllCells()) {
        System.out.println(cell + ": " + cell.getBoundsInParent());
    }

}

As an alternative you can invoke whatever happens after the graph creation into a Platform.runLater, i. e.:

Platform.runLater(() -> {
    for( Cell cell: graph.getModel().getAllCells()) {
        System.out.println(cell + ": " + cell.getBoundsInParent());
    }
});
Roland
  • 18,114
  • 12
  • 62
  • 93
  • 1
    Thank you for your answer. I tried it and the latter version with Platform.runLater worked whereas the former only had non-zero values for minX/minY. – Andrew Mar 23 '16 at 10:23
  • 1
    What if I want to create a button with user's click on another button and get the size of the newly created button? – Eftekhari Apr 27 '20 at 16:37
  • @Eftekhari you can refer to this question: https://stackoverflow.com/questions/66694228/javafx-size-of-a-button-after-adding-it-to-a-container/ – Dávid Tóth Mar 19 '21 at 07:44