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

Why added two ColumnConstraints in FXML?

我是 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>

A GridPane 有一个 或更多 列。每列都可以有约束,这是通过将 ColumnConstraints 个实例添加到 GridPane#getColumnConstraints() 列表来实现的。来自文档:

Returns list of column constraints. Column constraints can be added to explicitly control individual column sizing and layout behavior. If not set, column sizing and layout behavior is computed based on content. Index in the ObservableList denotes the column number, so the column constraint for the first column is at the position of 0 [emphasis added].

注意:如果您不知道,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 的行为是相同的,除了约束适用于行而不是列(很明显)。