how to add text to rectangle in javafx

Viewed 294

i have small homework with stackpane and gridpane. i build gridpane and small rectangles but when i try to add to text to that rectangles it does not work. thank you for any help.

                Text text = new Text(rand1);

                text.setFill(Color.BLACK);
                text.setFont(Font.font("Calibri",FontWeight.BOLD,FontPosture.REGULAR,12));
                text.setX(30);
                text.setY(30);

                Rectangle rec = new Rectangle(x,y,30,30);
                rec.setFill(color);
                stackPane.getChildren().addAll(rec,text);

enter image description here

1 Answers

Your code works for me but my guess is that the text is being set behind the Rectangle try putting text.toFront(); after you add them to the StackPane

In this example I put the code inside a button action so you can see how it works but you can just call the action

Runnable Example

public class Main extends Application {


    @Override
    public void start(Stage primaryStage) {
        Text text = new Text("rand1");

        text.setFill(Color.BLACK);
        text.setFont(Font.font("Calibri", FontWeight.BOLD, FontPosture.REGULAR,12));
        text.setX(30);
        text.setY(30);

        Rectangle rec = new Rectangle(10,10,30,30);
        rec.setFill(Color.RED);
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(text, rec);

        //Call the line below in your code 
        //text.toFront();

        Button button = new Button("text.toFront()");
        button.setOnAction(event -> text.toFront());

        primaryStage.setScene(new Scene(new VBox(stackPane, button)));
        primaryStage.sizeToScene();
        primaryStage.show();

    }
}

Doc

/**
 * Moves this {@code Node} to the front of its sibling nodes in terms of
 * z-order.  This is accomplished by moving this {@code Node} to the
 * last position in its parent's {@code content} ObservableList.
 * This function has no effect if this {@code Node} is not part of a group.
 */
public void toFront()
Related