Search code examples
javajavafxjavafx-css

The rule "-fx-text-alignment" doesn't work?


I'm creating a simple user interface with JavaFX, where some labels showing texts are used. I tried to move text to the center of labels with the rule:

-fx-text-alignment: center

yet it doesn't work and text is still located on the left by default. I have also checked that I haven't used any other rules that could override this. Any ideas? Here is the css code:

#subtitle
{
    -fx-font: bold italic 18pt "Arial";
    -fx-text-alignment: center;
    -fx-effect: dropshadow( one-pass-box, black, 8, 0.0, 2, 0 );
    -fx-text-fill: #1ebd1e;
}

Java code:

Label title = new Label("Trees");
title.setId("subtitle");
grid.add(title, 0, 0, 2, 1);

enter image description here


Solution

  • You can solve this problem using the code below:

    Label title = new Label("Trees");
    title.setId("subtitle");
    GridPane.setHalignment(title, HPos.CENTER);
    gridpane.add(title, 0, 0, 2, 1);
    

    This is the result I got:

    enter image description here

    Note: The -fx-text-alignment tag is going to center the text inside the label's borders. If the label's width is exactly the size it needs to fit the text, you have no changes about the alignment, but if you set a width bigger than the text needs you can align the text inside the Label's borders.