JavaFX - Layout Stackpane


If we use the Stack Pane, the nodes are arranged on top of another, just like in stack. The node added first is placed at the bottom of the stack and the next node is placed on top of it.

The class named StackPane of the package javafx.scene.layout represents the StackPane. This class contains a single property named alignment. This property represents the alignment of the nodes within the stack pane.

In addition to these, this class also provides a method named setMargin(). This method is used to set margin for the node within the stack pane.


The following program is an example of the StackPane layout. In this, we are inserting a Circle, Sphere and a Text in the same order.

Save this code in a file with the name

import javafx.application.Application; 
import javafx.collections.ObservableList; 
import javafx.geometry.Insets; 

import javafx.scene.Scene; 
import javafx.scene.layout.StackPane; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Circle; 
import javafx.scene.shape.Sphere;
import javafx.scene.text.Font; 
import javafx.scene.text.FontWeight; 
import javafx.scene.text.Text; 
import javafx.stage.Stage; 
public class StackPaneExample extends Application { 
   public void start(Stage stage) {                     
      //Drawing a Circle 
      Circle circle = new Circle(300, 135, 100); 
      //Drawing Sphere 
      Sphere sphere = new Sphere(50); 
      //Creating a text 
      Text text = new Text("Hello how are you"); 
      //Setting the font of the text 
      text.setFont(Font.font(null, FontWeight.BOLD, 15));     
      //Setting the color of the text 
      //setting the position of the text 
      //Creating a Stackpane 
      StackPane stackPane = new StackPane(); 
      //Setting the margin for the circle 
      stackPane.setMargin(circle, new Insets(50, 50, 50, 50));       
      //Retrieving the observable list of the Stack Pane 
      ObservableList list = stackPane.getChildren(); 
      //Adding all the nodes to the pane 
      list.addAll(circle, sphere, text); 
      //Creating a scene object 
      Scene scene = new Scene(stackPane);  
      //Setting title to the Stage 
      stage.setTitle("Stack Pane Example"); 
      //Adding scene to the stage 
      //Displaying the contents of the stage;  
   public static void main(String args[]){ 

Compile and execute the saved java file from the command prompt using the following commands.

java StackPaneExample

On executing, the above program generates a JavaFX window as shown below.