【问题标题】:JavaFx GridPane - how to center elementsJavaFx GridPane - 如何使元素居中
【发布时间】:2012-09-30 17:33:10
【问题描述】:

我有一个GridPane,里面填满了 1 个字母的标签。

这是一张图片:

代码如下:

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


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      哦,这很容易。我在错误的地方做了对齐。添加这个就可以了:

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

      还是谢谢。

      【讨论】:

      • import javafx.geometry.Pos 对于那些想知道的人。另外,他们为什么不把它称为 Position,就像 Java 通常会做的那样?
      【解决方案3】:

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

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

      <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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-09
        • 2017-03-21
        • 2014-04-13
        • 2017-02-11
        • 2015-12-14
        • 2021-03-17
        相关资源
        最近更新 更多