为什么要在FXML中添加两个ColumnConstraints?

问题描述 投票:0回答:1

我是JavaFX的新手,在我的sample.fxml文件中找到了两个ColumnConstraints,但我不知道为什么有两个<GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10" gridLinesVisible="true"> <columnConstraints> <ColumnConstraints percentWidth="100"/> <ColumnConstraints percentWidth="100"/> </columnConstraints> </GridPane> ,因为当我删除其中一个时,视图改变了。

GridPane
java javafx fxml gridpane
1个回答
1
投票

A ColumnConstraints具有一列[[或更多”列。每列都可以施加约束,这可以通过添加到GridPane#getColumnConstraints()列表的GridPane#getColumnConstraints()实例来实现。从文档中:

返回列约束的列表。可以添加列约束以显式控制各个列的大小和布局行为。如果未设置,则根据内容计算列的大小和布局行为。

ObservableList中的索引表示列号,因此第一列的列约束位于0的位置 [加重]。

注意:

如果您不知道,FXML文件仅描述对象图,然后FXMLLoader解析该文件并设置适当的属性或将元素添加到适当的集合。 <columnConstraints>元素引用上面提到的列表,并且ColumnConstraints实例被添加到该列表中。有关更多信息,请参见Introduction to FXML
如您所见,列表中ColumnConstraints的索引确定约束适用于哪一列。您的FXML文件添加了两个约束,这意味着您将同时为第一列和第二列添加约束。不过,公平地说,两列都占用100%的宽度是没有意义的。现在,如果sample.fxml文件是在发布时创建的(即,您所做的更改不多),并且您想知道

为什么您的工具会自动添加两个约束-我无法回答。 >请注意,没有要求每个索引都需要唯一的ColumnConstraints实例。换句话说,可以通过将同一实例多次添加到列表中来将同一实例用于多个列。在FXML中看起来像:

<GridPane fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10" gridLinesVisible="true"> <fx:define> <ColumnConstraints fx:id="colConstraints" percentWidth="100"/> </fx:define> <columnConstraints> <fx:reference source="colConstraints"/> <fx:reference source="colConstraints"/> </columnConstraints> </GridPane>

关于为什么删除ColumnConstraints之一后视图会发生变化,即使列中没有内容,约束的存在也会迫使该列存在。并且当列中没有内容时,如果删除约束,则该列将不复存在。

RowConstraints的行为是相同的,除了约束适用于行而不是列(显然)。”>

© www.soinside.com 2019 - 2024. All rights reserved.