中心在JavaFX中对齐GridPane的行

时间:2014-09-15 16:50:29

标签: java javafx gridpane

我在fxml中有一个GridPane,它有一个文本标题和4个按钮。 GridPane本身是居中对齐的,但所有按钮都在网格列内对齐。我知道如何使用Java代码更改项目的对齐方式,但这不是理想的情况,因为我希望使用FXML和CSS处理所有样式。任何人都可以建议在JavaFX的GridPane视图中居中对齐单元格元素的最佳方法吗?

3 个答案:

答案 0 :(得分:16)

要将GridPane的孩子设置为与中心对齐,您需要设置子节点的HalignmentValignment

在Java代码中,您可以执行类似的操作:

GridPane.setHalignment(node, HPos.CENTER); // To align horizontally in the cell
GridPane.setValignment(node, VPos.CENTER); // To align vertically in the cell

在FMXL中,您可以通过以下方式获得类似的效果:

<GridPane>
      ... // other properties
     <children>
        <Button mnemonicParsing="false" text="Button" GridPane.halignment="CENTER" GridPane.valignment="CENTER" />
     </children>
</GridPane>

如果要将特定列或行的所有节点对齐,则可以采用更简单的方法实现此目的。您可以创建ColumnConstraintsRowConstraints并将其添加到GridPane,而不是向节点添加halignment / valignment

<GridPane>
    <columnConstraints>
        <ColumnConstraints hgrow="SOMETIMES" halignment="CENTER" minWidth="10.0" prefWidth="100.0" />
         ... // More constraints for other columns
    </columnConstraints>
    <children>
         <Button mnemonicParsing="false" text="Button" />
    </children>
</GridPane>

您也可以同样添加RowConstraints

答案 1 :(得分:4)

在FXML中:

<GridPane ...>
  <columnConstraints>

    <!-- one of these for each column: you can obviously have other properties set here if needed -->
    <ColumnConstraints halignment="CENTER" />

  </columnConstraints>
</GridPane>

答案 2 :(得分:0)

您需要单独对齐GridPane中的每个对象,而不是GridPane本身。

要执行此操作,请转到布局:对象名称(例如按钮),然后在HAlignment处选择“中心”。