Mourad Qqch
Mourad Qqch

Reputation: 459

How to align center Label in JavaFX / FXML?

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.

Upvotes: 9

Views: 53110

Answers (1)

James_D
James_D

Reputation: 209319

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.

Upvotes: 21

Related Questions