How to position a button (or any GUI element) in a JavaFX scene?
layoutX
and layoutY
<Button text="Button" layoutX="50" layoutY="100" />
In FXML, you can use the layoutX
and layoutY
properties that are inherited from javafx.scene.Node
.
According to the JavaFX Documentation:
layoutX
Defines the x coordinate of the translation that is added to this Node's transform for the purpose of layout.
layoutY
Defines the y coordinate of the translation that is added to this Node's transform for the purpose of layout.
The example below results in a window in which a Button
element is positioned with an x-coordinate of 50
and a y-coordinate of 100
.
sample.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.Scene?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.control.Button?>
<Scene>
<Pane prefWidth="300" prefHeight="300">
<!-- Button Positioned Using layoutX and layoutY -->
<Button text="Button" layoutX="50" layoutY="100" />
</Pane>
</Scene>
Main.java
package sample;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Scene scene = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Window Title");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Note: You can also use the
setLayoutX()
andsetLayoutY()
methods to set the values of thelayoutX
andlayoutY
properties dynamically in the controller, rather than through the markup. Additionally, you can use thelayoutX
andlayoutY
tags (i.e.<layoutX>
and<layoutY>
) within the UI element tag to set the x-coordinates and y-coordinates inside of the FXML markup as an alternative to using attributes.
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();
}
}