在GridPane JAVAFX中水平居中

时间:2016-11-07 18:16:26

标签: java javafx row center gridpane

我想在GridPane中水平居中一行。我知道如何水平居中一列(root.getColumnConstraints().get(0).setHalignment(HPos.CENTER);),但我无法找到行的这种方法。我只能更改列的Halignment属性和行的Valignment属性。但我需要的是行的Halignment,它不存在。那我怎么能这样做呢?

This is what I want at the end

1 个答案:

答案 0 :(得分:0)

对于整行的使用约束不可能这样做,但您可以使用GridPane.setHalignment连续设置所有Node的属性,该属性优先于ColumnConstraints }。

示例

@Override
public void start(Stage primaryStage) {
    Text text00 = new Text("text");
    Text text01 = new Text("text");
    Text text02 = new Text("text");
    Text text10 = new Text("text");
    Text text11 = new Text("text");
    Text text12 = new Text("text");
    GridPane gridPane = new GridPane();

    ColumnConstraints cConstraints = new ColumnConstraints();
    cConstraints.setHalignment(HPos.LEFT);
    cConstraints.setHgrow(Priority.ALWAYS);
    gridPane.getColumnConstraints().addAll(cConstraints, cConstraints);
    gridPane.addColumn(0, text00, text01, text02);
    gridPane.addColumn(1, text10, text11, text12);

    GridPane.setHalignment(text11, HPos.CENTER);
    GridPane.setHalignment(text01, HPos.CENTER);

    Scene scene = new Scene(gridPane);

    primaryStage.setScene(scene);
    primaryStage.show();
}

请注意,您可以在将节点添加到GridPane之后通过迭代子节点来执行此操作:

int alignRow = 1;
for (Node n : gridPane.getChildren()) {
    Integer row = GridPane.getRowIndex(n);
    int rowNumber = row == null ? 0 : rowNumber.intValue();
    if (rowNumber = alignRow) {
        GridPane.setHalignment(n, HPos.CENTER);
    }
}