gpt4 book ai didi

javafx - VBox .getHeight() 直到 .setOnAction 完成后才改变

转载 作者:行者123 更新时间:2023-12-04 23:11:57 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Get the height of a node in JavaFX (generate a layout pass)

(1 个回答)


1年前关闭。




所以我不确定如何在我尝试过的 .setOnAction 事件期间计算节点的高度 .requestLayout()/.applyCss()不知道还有什么可尝试的 我试图在添加节点后找到 vBox 的高度,但它只是在添加新节点之前打印节点的高度

public class Main extends Application {

@Override
public void start(Stage stage) {
VBox vBoxContainer = new VBox();
vBoxContainer.setAlignment(Pos.CENTER);
vBoxContainer.setPrefSize(200,200);

VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
for (int i = 0; i < 5; i++)
vBox.getChildren().add(new Label("newLabel"));
vBoxContainer.getChildren().add(vBox);

Button button = new Button("Add Label");
button.setOnAction(event -> {
System.out.println("Height Before new Label:"+vBox.getHeight());
vBox.getChildren().add(new Label("newLabel"));
//here is where I was adding code to produce expected result
System.out.println("Height After new Label:"+vBox.getHeight());
});

Button checkButton = new Button("Print VBox Height");
checkButton.setOnAction(event -> System.out.println("VBox Height:"+vBox.getHeight()));

vBoxContainer.getChildren().addAll(button, checkButton);

stage.setScene(new Scene(vBoxContainer));
stage.show();
}
}

运行示例并单击将标签添加到 vBox 的按钮并输出

实际结果:
Height Before new Label:85.0
Height After new Label:85.0

预期结果:
Height Before new Label:85.0
Height After new Label:102.0

但是,如果您然后单击 Print VBox Height 按钮,它将显示正确的高度:
VBox Height:102.0

最佳答案

您可以尝试向 VBox's 添加一个监听器高度属性。

VBox vBoxContainer = new VBox();
vBoxContainer.setAlignment(Pos.CENTER);
vBoxContainer.setPrefSize(200, 200);

VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
vBoxContainer.getChildren().add(vBox);
vBox.heightProperty().addListener((observable, oldValue, newValue) -> {
System.out.println("Height changed to: " + newValue.doubleValue());
if(newValue.doubleValue() > 100)
{
//do something!
}
});
for (int i = 0; i < 5; i++) {
vBox.getChildren().add(new Label("newLabel"));
}
Button button = new Button("Add Label");
button.setOnAction(event -> {
vBox.getChildren().add(new Label("newLabel"));
});
Button checkButton = new Button("Print VBox Height");
checkButton.setOnAction(event -> System.out.println("VBox Height:" + vBox.getHeight()));

vBoxContainer.getChildren().addAll(button, checkButton);
stage.setScene(new Scene(vBoxContainer));
stage.show();

关于javafx - VBox .getHeight() 直到 .setOnAction 完成后才改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58561811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com