为什么 JavaFX 节点在应用 css 后在初始化方法中有错误的大小?

Why does JavaFX Node have wrong sizes in initialize method after css is applied?

我有一个包含多个 AnchorPane 的 VBox。我决定向这些 AnchorPane 添加 css 样式:-fx-border-width。但是 VBox 在另一个“主”AnchorPane 内,而主 AnchorPane 在 ScrollPane 内。如果我将 css 添加到元素,则不会显示 ScrollPane 中的所有元素。为了测试,我将 border-width 设置为 0 0 10 0。我有 20 个元素,因此在将样式应用于 VBox 的每个元素后 VBox 的总大小应增加 200。在控制器的 intiailize() 方法中,调用之后VBox 的 layout() 和 applyCss()、getHeight( ) returns 1200(如果我不添加 css,我知道这是 VBox 的高度)。然后对于主 anchorPane,我正在设置高度 setPrefHeight(vbox.getHeight())。但在我的应用程序最终运行后,我看到 VBox 大小如预期的那样为 1400。但是 AnchorPane 的大小仍然是 1200,因此如果我滚动到最后,ScrollPane 中的一些元素将不可见。我该如何解决?

@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
    for (int i = 0; i < 20; i++) {
        addElementsToVBox();
    }

    vbox.applyCss();
    vbox.layout();

    mainAnchorPane.applyCss();
    mainAnchorPane.layout();

    System.out.println(vbox.getHeight()); //in my case will be 1200, 
    //but after the application will complete the loading, vbox.getHeight() will return 1400
    //if I would invoke it from button's onAction() for example

    mainAnchorPane.setPrefHeight(vbox.getHeight());
}

private void addElementsToVBox() {
    Label label = new Label();
    label.setText("Test");
    
    AnchorPane anchorPane = new AnchorPane();
    anchorPane.getChildren().add(label);
    anchorPane.setPadding( new Insets(2, 0, 2, 0) );
    anchorPane.setStyle("-fx-border-width: 0 0 10 0; -fx-border-color: black");
    anchorPane.applyCss();
    anchorPane.layout();

    vbox.getChildren().add(anchorPane);
}

在我的例子中,我使用的是 mainAnchorPane.setPrefHeight(vbox.getHeight()),因为经过实验我注意到如果没有该方法,mainAnchorPane 不会改变高度。那是因为我在 SceneBuilder 中为 AnchorPane 设置了精确的 pref 高度值。但是在设置 USE_COMPUTED_SIZE 之后,我的 AnchorPane 将具有我实际想要的大小。所以我只需要:

set computed size for all fields