JavaFx GridPane - how to center elements
Asked Answered
E

3

12

I have a GridPane filled with 1-letter-labels.

Here is an 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 have put them in a HBox and gave them spacing. I tried to make the textAlignment of the label to CENTER, but that doesn't work of course.

I tried this also:

gp.setAlignment(Pos.CENTER);

Has anybody an idea? Thanks!

Ethnomusicology answered 10/10, 2012 at 9:25 Comment(0)
E
12

oh, that was easy. i did the alignment on the wrong place. adding this will do the job:

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

thanks anyway.

Ethnomusicology answered 10/10, 2012 at 9:41 Comment(1)
import javafx.geometry.Pos for those who wondered. Also, why didn't they call it Position, as Java would normally do?Asymptote
R
29
Renegado answered 19/6, 2013 at 9:23 Comment(0)
E
12

oh, that was easy. i did the alignment on the wrong place. adding this will do the job:

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

thanks anyway.

Ethnomusicology answered 10/10, 2012 at 9:41 Comment(1)
import javafx.geometry.Pos for those who wondered. Also, why didn't they call it Position, as Java would normally do?Asymptote
L
8

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

or you can define a contraint to the GridPane that contains the 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>
Lexie answered 13/9, 2018 at 22:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.