JavaFx GridPane - how to center elements

I have a GridPane filled with 1 letter inscriptions.

Here is the image:

image

Here is the code:

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

How can I center the characters?

I put them in the HBox and gave them an interval. I tried to make textAlignment labels for CENTER , but this of course does not work.

I tried this as well:

 gp.setAlignment(Pos.CENTER); 

Does anyone have an idea? Thanks!

+11
source share
3 answers

Oh, that was easy. I did alignment in the wrong place. adding that this will complete the task:

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

thanks anyway.

+11
source
+28
source

You can use the setAligment(Pos.CENTER) property of your element-

or you can define a contraint for a GridPane that contains elements

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

Example:

 <?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> 
+4
source

Source: https://habr.com/ru/post/927333/


All Articles