Centre a label on a node in JavaFX 2.0


I'd like to be able to display a node with a particular label centred on the node - eg. a circle or rectangle node for instance with the label in the centre. This seems like it should be trivial and I'm sure it is but the relatively sparse documentation / tutorials on the web mean I can't seem to find the answer!

At the moment I can display a label on a node no problem (by default it appears so the top left of the label starts in the centre which isn't what I want) or set a label to appear to the right of the node (by setting a label "for" a particular node) but not position it in the middle! Can anyone shed some light on this one?

10/13/2011 4:17:59 PM

Accepted Answer

I'm betting your looking for something other then a layout, but the StackPane provides this type of functionality.

From the tutorial: Working with Layouts


The StackPane layout pane places all of the nodes within a single stack with each new node added on top of the previous node. This layout model provides an easy way to overlay text on a shape or image or to overlap common shapes to create a complex shape. Figure 1-6 shows a help icon that is created by stacking a question mark on top of a rectangle with a gradient background.

enter image description here

Code from the tutorial

Example 1-4 Create a Stack Pane

StackPane stack = new StackPane();
Rectangle helpIcon = new Rectangle(35.0, 25.0);
helpIcon.setFill(new LinearGradient(0,0,0,1, true, CycleMethod.NO_CYCLE,
new Stop[]{
new Stop(0,Color.web("#4977A3")),
new Stop(0.5, Color.web("#B0C6DA")),
new Stop(1,Color.web("#9CB6CF")),}));

Text helpText = new Text("?   ");
helpText.setFont(Font.font("Amble Cn", FontWeight.BOLD, 18));

stack.getChildren().addAll(helpIcon, helpText);
stack.setAlignment(Pos.CENTER_RIGHT);     // Right-justify nodes in stack

HBox.setHgrow(stack, Priority.ALWAYS);    // Give stack any extra space
hbox.getChildren().add(stack);            // Add to HBox from Example 1-2
10/14/2011 1:36:03 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow