JavaFX AnchorPane Layout


AnchorPane layout JavaFX:

  • AnchorPane is similar to BorderPane as it also have top, bottom, left, right, and centre.
  • But difference is that it is free flow layout.
  • That means we can place node anywhere using some method.

Methods used in AnchorPane:


XYZ= top ,bottom etc.

These methods put the node where we want to put.

For example :

AnchorPane root = new AnchorPane();
Button bt=new Button("top button");

// for top button
        AnchorPane.setTopAnchor(bt, 50.0);
        AnchorPane.setLeftAnchor(bt, 30.0);
        AnchorPane.setRightAnchor(bt, 10.0);

Output is :

javafx AnchorPane Layout, AnchorPane Layout

Example of AnchorPane layout :

package javafxtuts;

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

 * @author javafxtuts
public class Javafxtuts extends Application {
    public void start(Stage primaryStage) {
       AnchorPane root = new AnchorPane();
        Button bt=new Button("top button");
        Button bb=new Button("bottom button");
        Button bl=new Button("left button");
        Button br=new Button("right button");
        // for top button
        AnchorPane.setTopAnchor(bt, 10.0);
        AnchorPane.setLeftAnchor(bt, 30.0);
        AnchorPane.setRightAnchor(bt, 10.0);
        // for bottom button
        AnchorPane.setTopAnchor(bb, 230.0);
        AnchorPane.setLeftAnchor(bb, 20.0);
        AnchorPane.setRightAnchor(bb, 30.0);
        // for left button
        AnchorPane.setTopAnchor(bl, 60.0);
        AnchorPane.setLeftAnchor(bl, 10.0);
        AnchorPane.setRightAnchor(bl, 260.0);
        // for right button
         AnchorPane.setTopAnchor(br, 60.0);
        AnchorPane.setLeftAnchor(br, 260.0);
        AnchorPane.setRightAnchor(br, 5.0);
        //add childeren node(buttons)
        root.getChildren().addAll(bt, bb,bl,br);
        Scene scene = new Scene(root, 350, 300);

     * @param args the command line arguments
    public static void main(String[] args) {

Output :

javafx AnchorPane, AnchorPane example

Explaination of AnchorPane layout code:

    • It is pane where we can give absolute position of every node using methods setXYZAnchor() AS

setTopAnchor(button ,10.0);

  • it set position of button 10px from top.
  • getchildren() : is a method which get list of children node.
  • addAll() :to add more than one children.

Leave A Reply