gpt4 book ai didi

javafx - 获取 StackPane 的宽度

转载 作者:行者123 更新时间:2023-12-02 00:22:48 33 4
gpt4 key购买 nike

我不知道如何获得 StackPane 的宽度:
如果我引用 http://docs.oracle.com/javafx/2.0/api/javafx/scene/layout/StackPane.html ,StackPane 的尺寸应该适应它的内容:

A stackpane's parent will resize the stackpane within the stackpane's resizable range duringlayout. By default the stackpane computes this range based on its content as outlined in thetable below.

preferredWidth left/right insets plus the largest of the children's pref widths.


这里的语法是 scala,但问题涉及 javafx :
import javafx.scene.layout.StackPane
import javafx.scene.shape.Rectangle

class Bubble() extends StackPane {
val rect = new Rectangle(100, 100)

getChildren.add(rect)

println(rect.getWidth)
println(this.getWidth)
}

Output :
>> 100.0
>> 0.0 <- Why isn't it 100 ?
这是一个错误还是期待的行为?如何获得 StackPane 的内容宽度?
谢谢

最佳答案

布局管理器(实际上是所有可调整大小的对象)在实际显示应用程序之前不会更新它们的边界。 Rectangle 给出宽度 100,因为它是构造函数的默认值。

见下一个代码:

@Override
public void start(Stage stage) throws Exception {
StackPane root = new StackPane();
Rectangle rect = new Rectangle(100, 100);
root.getChildren().add(rect);

// 100 - 0
System.out.println(rect.getWidth());
System.out.println(root.getWidth());

stage.setScene(new Scene(root));

// 100 - 0
System.out.println(rect.getWidth());
System.out.println(root.getWidth());

stage.show();

// 100 - 100
System.out.println(rect.getWidth());
System.out.println(root.getWidth());
}

因此,您需要等待 StackPane 显示。或者在这件事上更好地依赖 JavaFX 并使用绑定(bind)。例如。
    stage.titleProperty().bind(root.widthProperty().asString());

关于javafx - 获取 StackPane 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10107624/

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