JavaFX code for responsive layout

This code creates a responsive layout using a BorderPane as the root layout, with an HBox in the top region containing two buttons. The spacing between the buttons adjusts based on the width of the scene using a listener on the scene’s width property

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ResponsiveLayoutExample extends Application {

    public void start(Stage primaryStage) {

        // Create a border pane as the root layout
        BorderPane root = new BorderPane();

        // Create an HBox for the top of the border pane
        HBox topBox = new HBox();
        topBox.setPadding(new Insets(10, 10, 10, 10));

        // Create two buttons for the top HBox
        Button button1 = new Button("Button 1");
        Button button2 = new Button("Button 2");

        // Add the buttons to the top HBox
        topBox.getChildren().addAll(button1, button2);

        // Set the top of the border pane to the HBox

        // Create a scene with the root layout
        Scene scene = new Scene(root, 400, 300);

        // Set the stage to the scene and show it

        // Add a listener to the scene's width property to adjust the top HBox spacing
        scene.widthProperty().addListener((observable, oldWidth, newWidth) -> {
            topBox.setSpacing(newWidth.intValue() / 20);

    public static void main(String[] args) {

Leave a Reply