JavaFX AnchorPane Layout Tutorial with Examples

View more Tutorials:

Websites to learn foreign languages for free:
Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- AnchorPane Layout

AnchorPane is a container, which is similar to BorderPane. BorderPane is divided into 5 separate areas in order to place subcomponent on while AnchorPane is divided into 5 areas in order to anchor on. Note that 5 areas of AnchorPane is 5 logic areas but no 5 real areas.
A subcomponent lying in  AnchorPane can be anchored into one or more logic areas of AnchorPane.
The below image illustrates a subcomponent which lies in AnchorPane and is anchored on the the left and right sides of AnchorPane. When AnchorPane changes the length, the length of subcomponents will be also accordingly changed.
Subcomponents can be anchored on 4 sides of AnchorPane:

2- AnchorPane example


package org.o7planning.javafx.anchorpane;

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

public class AnchorPaneDemo extends Application {

   public void start(Stage primaryStage) throws Exception {
       AnchorPane root = new AnchorPane();
       Button button1 = new Button("(B1) Top + Left + Right");

       Button button2 = new Button("(B2) Top + Left + Right");
       Button button3 = new Button("(B3) Top + Left + Right");

       Button button4 = new Button("(B4) Top + Left + Right + Bottom");

       // (B1) Anchor to the Top + Left + Right
       AnchorPane.setTopAnchor(button1, 40.0);
       AnchorPane.setLeftAnchor(button1, 50.0);
       AnchorPane.setRightAnchor(button1, 70.0);

       // (B2) Anchor to the Top + Left + Right
       AnchorPane.setTopAnchor(button2, 90.0);
       AnchorPane.setLeftAnchor(button2, 10.0);
       AnchorPane.setRightAnchor(button2, 320.0);

       // (B3) Anchor to the Top + Left + Right
       AnchorPane.setTopAnchor(button3, 100.0);
       AnchorPane.setLeftAnchor(button3, 250.0);
       AnchorPane.setRightAnchor(button3, 20.0);

       // (B4) Anchor to the four sides of AnchorPane
       AnchorPane.setTopAnchor(button4, 150.0);
       AnchorPane.setLeftAnchor(button4, 40.0);
       AnchorPane.setRightAnchor(button4, 50.0);
       AnchorPane.setBottomAnchor(button4, 45.0);

       // Add buttons to AnchorPane
       root.getChildren().addAll(button1, button3, button2, button4);

       Scene scene = new Scene(root, 550, 250);

       primaryStage.setTitle("AnchorPane Layout Demo (o7planning.org)");

   public static void main(String[] args) {

Running the example:

3- Design AnchorPanel with Scene Builder

  • File/New/Other...
Add the components into AnchorPane:
Anchor the subcomponents to the sides of AnchorPane:

View more Tutorials: