Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align center Label in JavaFX / FXML?

Tags:

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.

like image 767
Mourad Qqch Avatar asked May 30 '16 21:05

Mourad Qqch


People also ask

How do I change a label in JavaFX?

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.

How do you initialize a label in JavaFX?

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.

What is FX ID in FXML?

The fx:id is the identity associated to component in fxml to build a controller, and the id is used for css.

What is the difference between text and label in JavaFX?

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.


1 Answers

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.

like image 64
James_D Avatar answered Sep 17 '22 11:09

James_D