【发布时间】:2018-11-01 20:27:49
【问题描述】:
当我在我的 Main (JavaFX) 类的 start 方法中运行以下代码时,我得到了奇怪的结果。窗口被显示,但pane(带有绿色边框)的宽度为 0。它应该与容器的高度具有相同的宽度,因为我将 prefWidth 绑定到了 height 属性。
然后,当我调整窗口大小时,绑定生效,窗格变为正方形。请注意,如果我最大化窗口,它也不会应用绑定。
谢谢!
//Create a pane with a min width of 10 and a green border to be able to see it
Pane pane = new Pane();
pane.setStyle("-fx-border-color: green; -fx-border-width: 2");
//Bind the pane's preferred width to the pane's height
pane.prefWidthProperty().bind(pane.heightProperty());
//Put the pane in a vbox that does not fill the stage's width and make the pane grow in the vbox
VBox container = new VBox(pane);
container.setFillWidth(false);
VBox.setVgrow(pane, Priority.SOMETIMES);
//Show the vbox
primaryStage.setScene(new Scene(container, 600, 400));
primaryStage.show();
【问题讨论】:
-
啊,终于。我一直怀疑如果您使用绑定来管理布局,可能会发生这样的事情;我只是还没有遇到一个例子。谢谢:)。
-
我认为有一些因素导致了这种行为。首先,绑定是惰性求值的。只要 JavaFX 场景图渲染脉冲不调用
prefWidthProperty的 getter,那么prefWidthProperty将保持旧值,并将invalid设置为true。显然,JavaFX 不会在每个脉冲都查询这个值,这就是绑定似乎不起作用的原因。您可以用ChangeListener替换它应该可以工作 - 但它完全基于我的理解。 -
@Jai 使用更改侦听器:
pane.heightProperty().addListener((obs, oldH, newH) -> pane.setPrefWidth(newH.doubleValue()));产生相同的行为...我认为这只是布局代码中的操作顺序。 -
@James_D 我明白了.. 好吧,几个月前我在玩布局,类似于 OP 所做的。一些布局行为很奇怪,比如 OP 提到的这个问题。
-
@Jai Sure;使用绑定或侦听器对于执行布局并不可靠。您无法控制是否针对当前布局通道及时更新属性。从理论上讲,您可能会使用这些技术创建堆栈溢出异常(通过无限递归),但我怀疑库布局代码可以防止这种可能性。
标签: javafx layout javafx-bindings