StackPane
StackPane in JavaFX is a layout container that places all its children on top of each other, like a stack of cards.
- The first child is at the bottom.
- The last child is on top.
- You can align each child individually inside the stack.
It’s useful for:
- overlays
- background images
- popups
- icons with labels
Basic Example
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
public class StackPaneExample extends Application {
@Override
public void start(Stage stage) {
// Bottom rectangle (background)
Rectangle rect = new Rectangle(200, 100, Color.LIGHTBLUE);
// Button on top
Button button = new Button("Click Me");
// Create StackPane and add children
StackPane stackPane = new StackPane();
stackPane.getChildren().addAll(rect, button);
// Optional: center children
stackPane.setAlignment(Pos.CENTER);
Scene scene = new Scene(stackPane, 300, 200);
stage.setTitle("StackPane Example");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Result:
+----------------------+
| |
| [Click Me] | <- Button is on top of rectangle
| |
+----------------------+
Important Methods & Properties
stackPane.getChildren(); // access all children
stackPane.setAlignment(Pos.CENTER); // default alignment for all children
StackPane.setAlignment(node, Pos.BOTTOM_RIGHT); // individual child alignment
Example: Multiple Children with Different Alignments
StackPane stack = new StackPane();
Rectangle background = new Rectangle(300, 200, Color.LIGHTGRAY);
Button topLeft = new Button("Top Left");
Button bottomRight = new Button("Bottom Right");
stack.getChildren().addAll(background, topLeft, bottomRight);
// Align individual buttons
StackPane.setAlignment(topLeft, Pos.TOP_LEFT);
StackPane.setAlignment(bottomRight, Pos.BOTTOM_RIGHT);
backgroundstays at the bottom- Buttons appear on top at their specified positions
FXML Version
<StackPane xmlns:fx="http://javafx.com/fxml" alignment="CENTER">
<children>
<Rectangle width="200" height="100" fill="LIGHTBLUE"/>
<Button text="Click Me"/>
</children>
</StackPane>
Use Cases
- Background image + overlay text or buttons
- Popups or modals
- Layered UI: monitor previews, icons, badges
- Card-like interface
Example for your app:
- A
StackPanecould show a monitor image as the bottom layer, and a label with the monitor name on top. - Or a wallpaper preview with a “Set Wallpaper” button overlaid.