【问题标题】:Center Align Rows of a GridPane in JavaFXJavaFX中GridPane的行居中对齐
【发布时间】:2014-11-09 06:28:19
【问题描述】:

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

【问题讨论】:

    标签: java javafx gridpane


    【解决方案1】:

    在 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】:

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

      为此,请转到布局:ObjectName(例如按钮),然后在 HAlignment 处选择 CENTER。

      【讨论】:

        【解决方案3】:

        要设置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

        【讨论】:

          猜你喜欢
          • 2019-01-08
          • 2016-07-31
          • 2019-04-14
          • 1970-01-01
          • 1970-01-01
          • 2017-03-21
          • 2016-05-28
          • 2017-04-18
          • 2012-09-30
          相关资源
          最近更新 更多