JavaFx GridPane – 如何集中元素

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

这是一张图片:

图片http://sofzh.miximages.com/java/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); 

有人有想法吗? 谢谢!

  • 您可以使用此GridPane.setHalignment(tmp[currArrPos], HPos.CENTER); 使用GridPane布局控件

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

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

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

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

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

    

例:

          
Interesting Posts