Michael Berry
Michael Berry

Reputation: 72264

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?

Upvotes: 1

Views: 9683

Answers (1)

jkaufmann
jkaufmann

Reputation: 924

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

StackPane

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")),}));
helpIcon.setStroke(Color.web("#D0E6FA"));
helpIcon.setArcHeight(3.5);
helpIcon.setArcWidth(3.5);

Text helpText = new Text("?   ");
helpText.setFont(Font.font("Amble Cn", FontWeight.BOLD, 18));
helpText.setFill(Color.WHITE);
helpText.setStroke(Color.web("#7080A0")); 

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

Upvotes: 5

Related Questions