无法确定按钮的宽度,因为 JavaFx 中 getWidth() 返回 0

And*_*rew 1 javafx

我正在开发一个必须显示树的应用程序。我从: JavaFX 中的图形可视化(如 yFiles)开始。树会显示,但对于调用 getWidth 方法或 getBoundsInLocal、getBoundsInParent、getLayoutBounds 的任何变体的 ButtonCell,getLayoutBounds 返回 0,而 getPrefWidth 返回 -1。

如何获取按钮的宽度和高度?

Rol*_*and 5

您必须在舞台显示之前添加组件并在舞台显示之后获取值,即:

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

}
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您可以将图形创建后发生的任何情况调用到 Platform.runLater 中,即:

Platform.runLater(() -> {
    for( Cell cell: graph.getModel().getAllCells()) {
        System.out.println(cell + ": " + cell.getBoundsInParent());
    }
});
Run Code Online (Sandbox Code Playgroud)