How add text in Rectangle in Javafx

fredsilva picture fredsilva · Aug 25, 2014 · Viewed 21.4k times · Source

How do I add a text at the center of a rectangle? I've been searching and have not found a way to do this.

See the class below:

public class Agent extends Rectangle{         

    public Agent() {
        setWidth(60);
        setHeight(60);
        setArcWidth(60);
        setArcHeight(60);                
        setFill(Color.BLUEVIOLET.deriveColor(0, 1.2, 1, 0.6));
        setStroke(Color.BLUEVIOLET);
     }    
}

Thanks!

Answer

ROMANIA_engineer picture ROMANIA_engineer · Aug 25, 2014

Add the Text element and the Agent (Rectangle) element in a StackPane.

Text text = new Text("...");
...
StackPane stack = new StackPane();
stack.getChildren().addAll(agent, text);