How to position a button (or any GUI element) in a JavaFX scene?

Milos Maksimovic picture Milos Maksimovic · Apr 5, 2012 · Viewed 68.5k times · Source

I am trying to put a JavaFX button in a specific place (specific coordinates) on a UI, but nothing is working. I'm guessing that there is a method that is used for this, but I can't find it.

Answer

Vinod CG picture Vinod CG · Apr 5, 2012

you can use pane. setLayoutX() and setLayoutY().

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;

public class Tester extends Application {


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

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Hello World!");
    Button btn = new Button();
    btn.setText("'Hello World'");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println("Hello World!");
        }
    });

    Pane root = new Pane();
    btn.setLayoutX(250);
    btn.setLayoutY(220);
    root.getChildren().add(btn);
    primaryStage.setScene(new Scene(root, 300, 250));
    primaryStage.show();
}
}