[英]Cannot determine width of button because getWidth() returns 0 in JavaFx
I am working on an application where I have to display a tree. 我正在开发必须显示树的应用程序。 I started from: Graph Visualisation (like yFiles) in JavaFX .
我开始于: JavaFX中的图形可视化(如yFiles) 。 The tree gets displayed, but for ButtonCell calling the method getWidth or any variant of getBoundsInLocal, getBoundsInParent, getLayoutBounds returns 0 and getPrefWidth returns -1.
树被显示,但是对于ButtonCell调用方法getWidth或getBoundsInLocal的任何变体,getBoundsInParent,getLayoutBounds返回0,而getPrefWidth返回-1。
How do I get the width and height of the button? 如何获得按钮的宽度和高度?
You have to add the components before the stage is shown and get the values after the stage is shown, ie: 您必须在显示阶段之前添加组件,并在显示阶段之后获取值,即:
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, ie: 或者,您可以调用图形创建后在Platform.runLater中进行的所有操作,即:
Platform.runLater(() -> {
for( Cell cell: graph.getModel().getAllCells()) {
System.out.println(cell + ": " + cell.getBoundsInParent());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.