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.
You can change the text of a label using its setText() method. This can be done while the application is running. Here is an example of setting the text of a JavaFX Label: label.
Syntax to Initialize JavaFX label is: Label lbl = new Label(); Here, the constructor can be of parameterized and non-parameterized, which depends on the requirement.
The fx:id is the identity associated to component in fxml to build a controller, and the id is used for css.
A Text is a geometric shape (like a Rectangle or a Circle), while Label is a UI control (like a Button or a CheckBox). In Swing, geometric shapes were restricted to the painting mechanism, while in JavaFX they can be used in more generic ways. And you can use a Text clipping, giving the node shape by the text.
You basically have two choices:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With