JavaFX: Stackpane and z-order

This entry is part 7 of 55 in the series JavaFX

A Stackpane could have a few children.  According to the definition of Stackpane, it lays out its few children in a back-to-front stack.

We will create a Stackpane with 3 children – a blue rectangle, a label and a text.

Label is very similar to text and they have very similar methods.

package javafxapplication4;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.text.Text;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class JavaFXApplication4 extends Application {

    public void start(Stage primaryStage) {

        primaryStage.setTitle("JavaFX Program");

        StackPane stackpane = new StackPane();

        Scene scene = new Scene(stackpane, 300, 250);

        Label lb = new Label();
        lb.setFont(Font.font("Times New Roman", 24));
        lb.setText("Hello World");

        //   stackpane.getChildren().add(lb);
        Text txt = new Text();
        txt.setFont(Font.font("Verdana", 36));
        txt.setText("Hi There");

        stackpane.getChildren().addAll(new Rectangle(200, 200, Color.BLUE), lb, txt);

     //   stackpane.getChildren().addAll(lb, new Rectangle(200, 200, Color.BLUE), txt);
     //   stackpane.getChildren().add(new Label("Go!"));;

    public static void main(String[] args) {


If you look at the output below, the Hi There text is in clear view.  It actually has a z-order of 2.  The blue rectangle has a z-order of 0.

So, mainly, it is due to this statement that we have:

     stackpane.getChildren().addAll(new Rectangle(200, 200, Color.BLUE), lb, txt);

You can try to change the statement and put them in different z-order.


Series Navigation<< JavaFX: Setting the text for display
JavaFX: Setting Constraints On Children >>