JavaFx GridPane - 如何集中元素

问题描述 投票:9回答:3

我有一个填充了1个字母标签的GridPane

这是一张图片:

image http://s1.directupload.net/images/121010/xu8o79sr.jpg

这是代码:

int charSpacing = 1;
int charsInWidth = 28;
int charsInHeight = 16;

double charWidth = 15;
double charHeight = 20;

GridPane gp = new GridPane();
gp.setAlignment(Pos.CENTER);

Label[] tmp = new Label[charsInHeight*charsInWidth];

String text = "W";
int currArrPos = 0;

for(int y = 0; y < charsInHeight; y++) {
    HBox hbox = new HBox(charSpacing);

    for(int x = 0; x < charsInWidth; x++) {
        tmp[currArrPos] = new Label(text);
        tmp[currArrPos].setTextFill(Paint.valueOf("white"));

        tmp[currArrPos].setMinHeight(charHeight);
        tmp[currArrPos].setMinWidth(charWidth);
        tmp[currArrPos].setMaxHeight(charHeight);
        tmp[currArrPos].setMaxWidth(charWidth);

        tmp[currArrPos].setStyle("-fx-border-color: white;");
        hbox.getChildren().add(tmp[currArrPos++]);

        if(x%2 == 0){
            text = "I";
        } else{
            text = "W";
        }
    }
    gp.add(hbox, 1, y);
}
guiDisplay.getChildren().add(gp);

如何将角色居中?

我把它们放在HBox并给它们间隔。我试图将标签的textAlignment制作成CENTER,但这当然不起作用。

我也尝试了这个:

gp.setAlignment(Pos.CENTER);

有人有想法吗?谢谢!

java user-interface positioning javafx-2 gridpanel
3个回答
26
投票

10
投票

哦,那很容易。我在错误的地方做了对齐。添加这个将完成工作:

tmp[currArrPos].setAlignment(Pos.CENTER);

不管怎么说,还是要谢谢你。


2
投票

您可以使用元素的setAligment(Pos.CENTER)属性 -

或者您可以将contraint定义为包含元素的GridPane

<columnConstraints>
    <ColumnConstraints halignment="CENTER" />
</columnConstraints>

例:

<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.ColumnConstraints?>

<GridPane fx:controller="app.graphics.Controller"
          xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
    <columnConstraints>
        <ColumnConstraints halignment="CENTER" />
    </columnConstraints>
</GridPane>
© www.soinside.com 2019 - 2024. All rights reserved.