JavaFX Layout AnchorPane Example

In this JavaFX source code example, we will see how to use the JavaFX AnchorPane layout with an example.

AnchorPane anchors the edges of child nodes to an offset from the anchor pane's edges. If the anchor pane has a border or padding set, the offsets will be measured from the inside edge of those insets. 

AnchorPane is a simple layout pane that must be used with other layout panes to create meaningful layouts.

JavaFX Layout AnchorPane Example

Let's create a JavaFX example that uses an AnchorPane and an HBox to position two buttons into the bottom-right corner of the window.
package sample;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        initUI(stage);
    }

    private void initUI(Stage stage) {

        AnchorPane root = new AnchorPane();

        Button okBtn = new Button("OK");
        Button closeBtn = new Button("Close");
        HBox hbox = new HBox(5, okBtn, closeBtn);

        root.getChildren().addAll(hbox);

        AnchorPane.setRightAnchor(hbox, 10d);
        AnchorPane.setBottomAnchor(hbox, 10d);

        Scene scene = new Scene(root, 300, 200);

        stage.setTitle("Corner buttons");
        stage.setScene(scene);
        stage.show();
    }

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




Comments