One of the annoying sharp edges in JavaFX is around text alignment, especially with regards to the Text node. In this tip, I’m going to skip using the Text node in favor of using the Label control, because it gives you better… uh… control over text placement. This is actually based on a trick I used to use with Swing all the time. If I wanted to center some text in a layout, I’d specify the space I wanted the text positioned within by setting the size of the label to match that space, and then I’d either position the text at the center, top, right, etc.
Using the same trick in JavaFX, I can cause some text to be right positioned. An additional benefit to using the Label control is that if the space isn’t big enough for the text, it can be elided using the textOverrun variable.
Label { width: bind 120 text: "Right Positioned Message!" font: Font { size: 10 } textFill: Color.BLACK hpos: HPos.RIGHT }
Anyway, it ain’t perfect but a good trick for the moment.
Irk!
First shocking sight: binding to a constant! Armless but useless.
Second wondering sight: setting the width for a resizable control…
The JavaFX 1.3 doc now states that quite clearly: “The Resizable’s layout width, which is set by the it’s parent during layout and should not be set directly by the application.”
Layout guru, Amy Fowler, recommends to set LayoutInfo’s width instead.
Binding the width is not useless at all, but is an alternate method for, essentially, overriding the width such that the layout container cannot set it. In fact, that is precisely why I use bind to the constant. Another way to accomplish essentially the same thing is to set the layoutInfo to have the specified width as you mention. I bet if you asked Amy which to do in this case, she’d not complain about the method I used 🙂
Ah, so you use bind to make the variable read-only? Now, that’s really tricky, indeed…
Perhaps a bit too much, as it is not obvious and thus not very readable (unless we are used to the trick?), but worth knowing.
Thanks for the explanation.
use instead of “width: bind 120” this:
layoutInfo: LayoutInfo {
width: width
}
I am using text alignment to right and textwrap as true.
But in this case if the width of the text is less that widht of the label then the text is aligned to left. If the text width is more than width of label then the the alignment is right as expected.
Could any one help on this issue.