John Seed
John Seed

Reputation: 387

How do I insert text into a shape in Javafx?

Using JavaFX I have created a simple rectangle object, and I want to be able to put a text object inside that rectangle, and for it to automatically stay aligned within the rectangle. The code I have to draw the rectangle is:

public static Scene createScene() {
        Group root = new Group();
        Scene scene = new Scene(root, Color.ALICEBLUE);

        Rectangle rectangle_red = new Rectangle();

        rectangle_red.setFill(Color.TRANSPARENT);
        rectangle_red.setStroke(Color.BLACK);
        rectangle_red.setX(50);
        rectangle_red.setY(50);
        rectangle_red.setWidth(200);
        rectangle_red.setHeight(100);
        rectangle_red.setCursor(Cursor.HAND);
        rectangle_red.setOnMousePressed(circleOnMousePressedEventHandler);
        rectangle_red.setOnMouseDragged(circleOnMouseDraggedEventHandler);        

        root.getChildren().add(rectangle_red);    

        return scene;
    }

The Handlers I have attached to the rectangle allow me to drag the rectangles anywhere in the window. How do I place text inside the rectangle such that it stays aligned as I drag the shape around the screen?

Upvotes: 5

Views: 13919

Answers (1)

trashgod
trashgod

Reputation: 205785

As illustrated in the last example seen here, the Animation Basics example TimelineEvents does this by adding a Circle and some Text to a StackPane, which centers its children by default. The stack can then be moved within an enclosing Group as a unit.

final Circle circle = new Circle(…);
final Text text = new Text (…);
final StackPane stack = new StackPane();
stack.getChildren().addAll(circle, text);
…
stack.setLayoutX(30);
stack.setLayoutY(30);

image

Upvotes: 10

Related Questions