Tuesday, 5 January 2021

JavaFX: Example of StackPane

StackPane is used to layout its children in back-to-front stack.

 

In this post, I am going to explain how to add a rectangle and text on top of rectangle using StackPane.

 

Step 1: Define a Rectangle widget.

Rectangle rectangle = new Rectangle(300, 100, Color.GRAY);

rectangle.setArcHeight(30);

rectangle.setArcWidth(30);

 

Step 2: Define a Text widget.

Text text = new Text("Hello World");

text.setFill(Color.LIGHTSALMON);

text.setFont(Font.font(null, FontWeight.SEMI_BOLD, 30));

 

Step 3: Define StackPane widget and add rectangle and text widgets to StackPane.

 

StackPane stackPane = new StackPane();

stackPane.getChildren().addAll(rectangle, text);

 

Step 4: Define a Scene instance and set stacPane ad root node to the Scene widget.

Scene scene = new Scene(stackPane, 500, 500, Color.WHITE);

 

Step 5: Set Scene instance to Stage instance.

primaryStage.setTitle("StackPane Demo");

primaryStage.setScene(scene);

primaryStage.show();

 

Find the below working application.

 

StackPaneDemo.java

package com.sample.app;

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

public class StackPaneDemo extends Application {

	@Override
	public void start(Stage primaryStage) throws Exception {

		Rectangle rectangle = new Rectangle(300, 100, Color.GRAY);
		rectangle.setArcHeight(30);
		rectangle.setArcWidth(30);

		Text text = new Text("Hello World");
		text.setFill(Color.LIGHTSALMON);
		text.setFont(Font.font(null, FontWeight.SEMI_BOLD, 30));

		StackPane stackPane = new StackPane();
		stackPane.getChildren().addAll(rectangle, text);

		Scene scene = new Scene(stackPane, 500, 500, Color.WHITE);

		primaryStage.setTitle("StackPane Demo");
		primaryStage.setScene(scene);
		primaryStage.show();

	}

	public static void main(String args[]) {
		launch(args);
	}
}

 

Run StackPaneDemo, you will see below screen.

 


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment