TL: DR version : instead of label.setAlignment(Pos.CENTER_RIGHT); use GridPane.setHalignment(label, HPos.RIGHT); .
JavaFX uses a top-down layout. Thus, a scene the size of a node root is equal to the size of the scene, the size of the node root and the position of each of its child nodes, depending on its layout strategy and the amount of space provided by the scene to it, each child node, then the sizes and position of its child nodes, depending on its own layout strategy and free space, etc. down the scene graph.
According to the documentation for Label , alignmentProperty
Indicates how text and graphics in the Labeled method should be aligned when there is empty space in Labeled.
Of course, the amount of space available for the label is determined by its parent, which in this case is a grid. Of course, you can learn about the grid layout strategy and how to configure it by reading its documentation . Shortly speaking:
By default, the grid panel will select each node its preferred size, and if the cell in which it is placed has additional space, the node is aligned in the upper left corner of the grid cell. The preferred size for the label is, of course, the calculated size: large enough to hold its contents. Therefore, you see that simply placing the label on the grid and setting the alignment on the label will not have any effect, because the label is large enough to hold its contents and there is no extra space for text / graphic alignment. You can visualize this by placing a background color or border on the label.
So, you can set the alignment on the CENTER_RIGHT , and then instruct the grid panel to increase the mark. Two things are needed for this: first tell the grid panels so that the label fills the cell width:
GridPane.setFillWidth(label, true);
and since the grid panel will also take into account the maximum size of the child node, and the default label uses its preferred size as the maximum size, allow label growth:
label.setMaxWidth(Double.MAX_VALUE);
Then the label will increase to the size of the cell, and therefore, if you also have
label.setAlignment(Pos.CENTER_RIGHT);
it aligns its own content on the right.
A more sensible approach is probably to tell the grid panels how to align the label in the cell:
GridPane.setHalignment(label, HPos.RIGHT);
Then let the label take the default size and alignment and everything will work.
You can also use the ColumnConstraints object to set the default alignment for all labels in a specific column, which is certainly more convenient if you are building a form.