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



我有一个VBox,它有几个AnchorPane。我决定将css样式添加到这些AnchorPane:-fx边框宽度中。但是VBox在另一个";主";AnchorPane,而主AnchorPanel位于ScrollPane内部。如果我将css添加到元素中,则不会显示ScrollPane中的所有元素。为了测试,我将边框宽度设为0 0 10 0。我有20个元素,所以在将样式应用于VBox的每个元素之后,VBox的总大小应该增加200。在控制器的initailize((方法中,在调用layout((和applyCss((之后,VBox的getHeight((返回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将具有我实际想要的大小。所以我只需要:

设置所有字段的计算大小

最新更新