Search code examples
javafxalertmultiple-monitors

How to set JavaFX-Alert into middle of actual monitor?


I've got a static method in a class without knowing anything about the Application, Scene oder Stage. But I want to show an Alert in the middle of the actual used monitor.

For example: My tool is on the right screen. I want to see the alert also there and not on the main screen.

My method:

private static Alert createAlert(AlertType type, String title, String header, String content) {
    Alert alert = new Alert(type);
    alert.setTitle(title);
    if (!header.isEmpty()) {
        alert.setHeaderText(header);
    }
    alert.setContentText(content);
    alert.setResizable(true);

    alert.setX(0); // set this into the middle of used monitor
    alert.setY(0); // 

    return alert;
}

How can I get the actual stage, scene or whatever to get its x- and y-position and use these information for setting x and y of the alert?


Solution

  • Assuming you have a reference to the current window, you can find the screen that contains it (e.g. contains its center point) with:

    Window currentWindow = ... ;
    Point2D windowCenter = new Point2D(currentWindow.getX() + currentWindow.getWidth()/2,
        currentWindow.getY() + currentWindow.getHeight()/2);
    
    Screen currentScreen = Screen.getScreens().stream()
        .filter(screen -> screen.getBounds().contains(windowCenter))
        .findAny().get();
    

    And then you can do

    Rectangle2D screenBounds = currentScreen.getBounds();
    double screenCenterX = screenBounds.getMinX() + screenBounds.getWidth()/2 ;
    double screenCenterY = screenBounds.getMinY() + screenBounds.getHeight()/2 ;
    

    and position the Alert accordingly...

    You need to know the current window though; it will be impossible to do this without that information. For example, your application might have multiple windows with different ones on different screens; the notion of "current screen" is simply not well defined in a case like that.