JavaFX Tutorial
In this tutorial, you will learn to center the stage on screen in JavaFX. I will show you two examples of centering the stage on screen in JavaFX. This would be great and simple. I hope this will help you with your JavaFX application. So, let’s get started.
How to center the stage on screen in JavaFX
Here’s how. Alright, to center the stage on screen in JavaFX. We will try to use the centerOnScreen() method. It sets the X and Y properties of the window so that it is centered on the current screen. Based on my experience, it looks like the Y coordinate is set a little higher than the actual center.
To actually center the stage on screen, we’ll try to use the centerOnScreen() method concept. So we will use the following methods: getPrimary() and getVisualBounds() methods. To do this, please see the example code below.
Example 1: We will use the centerOnScreen() method
Try this code and compare it to the second example.
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * * @author KENSOFT */ public class Center extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.centerOnScreen(); stage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
Example 2
This is how to center the stage on screen in JavaFX accurately. Try this code and compare it in the first example.
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.geometry.Rectangle2D; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Screen; import javafx.stage.Stage; /** * * @author KENSOFT */ public class Center extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); //This is how to center the stage on screen Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds(); stage.setX((screenBounds.getWidth() - stage.getWidth()) / 2); stage.setY((screenBounds.getHeight() - stage.getHeight()) / 2); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
Output
Watch this YouTube video to see the output of the example codes.