java 在 JavaFX 中居中对齐 GridPane 的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25852959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center Align Rows of a GridPane in JavaFX
提问by lhasson
I have a GridPane in fxml that has a Text Title and 4 Buttons. The GridPane itself is center aligned, but all the buttons are left aligned inside the column of the grid. I know how to change the alignment of the items using Java code but this is not the ideal situation, as I would like all styling to be handled using FXML and CSS. Can anyone suggest the best way to center align elements of a cell in a GridPane view of JavaFX?
我在 fxml 中有一个 GridPane,它有一个文本标题和 4 个按钮。GridPane 本身居中对齐,但所有按钮都在网格列内左对齐。我知道如何使用 Java 代码更改项目的对齐方式,但这不是理想的情况,因为我希望使用 FXML 和 CSS 处理所有样式。任何人都可以建议在 JavaFX 的 GridPane 视图中居中对齐单元格元素的最佳方法吗?
回答by ItachiUchiha
To set a child of GridPane
aligned to center, you need to set the Halignmentand Valignmentof the child node.
设置子节点GridPane
对齐居中,需要设置子节点的Halignment和Valignment。
In Java code you can do something similar to :
在 Java 代码中,您可以执行以下操作:
GridPane.setHalignment(node, HPos.CENTER); // To align horizontally in the cell
GridPane.setValignment(node, VPos.CENTER); // To align vertically in the cell
In FMXL you can achieve a similar effect by :
在 FMXL 中,您可以通过以下方式实现类似的效果:
<GridPane>
... // other properties
<children>
<Button mnemonicParsing="false" text="Button" GridPane.halignment="CENTER" GridPane.valignment="CENTER" />
</children>
</GridPane>
There is an easier way to achieve this if you want to align all the nodes of a particular column or row to be aligned in the same order. Instead of adding a halignment / valignment
to the node, you can create a ColumnConstraintsor a RowConstraintsand add them to the GridPane.
如果您希望将特定列或行的所有节点按相同顺序对齐,则有一种更简单的方法可以实现此目的。halignment / valignment
您可以创建ColumnConstraints或RowConstraints并将它们添加到GridPane,而不是向节点添加 。
<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>
You can similarly add RowConstraints
as well.
您也可以类似地添加RowConstraints
。
回答by James_D
In FXML:
在 FXML 中:
<GridPane ...>
<columnConstraints>
<!-- one of these for each column: you can obviously have other properties set here if needed -->
<ColumnConstraints halignment="CENTER" />
</columnConstraints>
</GridPane>
回答by Wilhelm Sorban
You need to align each object in the GridPane individually, not the GridPane itself.
您需要单独对齐 GridPane 中的每个对象,而不是 GridPane 本身。
To do this, go yo Layout: ObjectName (ex. Button), and at HAlignment choose CENTER.
为此,请转到 Layout: ObjectName (ex. Button),然后在 HAlignment 处选择 CENTER。