9

How can I center the text of a Label in javafx ? In the .css stylesheet or directly in the fxml.

I tried Label { -fx-text-alignment: center;} in the .css but it does not work. Even in the scene builder it does not work.

6
  • What is the parent of your Label in your FXML? May 30, 2016 at 21:54
  • @ItachiUchiha an AnchorPane May 30, 2016 at 22:13
  • Do you have multiple lines of text in the label, or is the text all on one line?
    – James_D
    May 30, 2016 at 23:04
  • I just have one line. I want to put an username on that label May 30, 2016 at 23:08
  • 2
    The textAlignment property is only relevant for multiple lines of text. It defines how each line is aligned in the rectangle that holds all the lines of text (basically a justify property).
    – James_D
    May 30, 2016 at 23:13

1 Answer 1

20

You basically have two choices:

  1. Use a layout pane that can center the label, and let the label be its "preferred size" (i.e. just big enough to hold the text), or
  2. Make the label fill the entire width of its container, and set its alignment property to center.

You said in the comments that you're using an AnchorPane as the label's parent. This generally isn't usually a particularly good choice for a layout pane (essentially you have to hardcode the bounds of each control), and you can't center things in it (not without a large amount of work, anyway). So with an anchor pane as parent, you are reduced to choice 2:

label.setMaxWidth(Double.MAX_VALUE);
AnchorPane.setLeftAnchor(label, 0.0);
AnchorPane.setRightAnchor(label, 0.0);
label.setAlignment(Pos.CENTER);

Obviously, all that can be set in FXML too.

In general, though, I would recommend using a more appropriate layout pane and setting the appropriate properties on that layout pane to center the label.

2
  • Thank you for your anwer, I changed the AnchorPane to a VBox and I worked :) May 31, 2016 at 8:56
  • @James_D What if we don't add the 1st line? I omitted 1st line and it worked.
    – Halil
    Feb 1, 2017 at 5:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.