Zephyr
Zephyr

Reputation: 10253

How to ensure application window is visible at launch?

I have an application that is usually run on a dual-monitor setup. I also save the currently size and position of the window when it exits and load it again when launching the app.

My problem comes from situations where one of the monitors is either removed or the resolution changed. If I save the x and y position of the window and it was last visible on the now-absent monitor, it is out of view when the program is launched again.

Here is the code I use to in my Main.java:

double x = Settings.getWindowX();
double y = Settings.getWindowY();
double h = Settings.getWindowH();
double w = Settings.getWindowW();

primaryStage.setScene(mainScene);
primaryStage.setX(x);
primaryStage.setY(y);
primaryStage.setWidth(w);
primaryStage.setHeight(h);

My goal is to check if the window is within the visible boundaries of the available monitors and, if not, reset the x, y to 100, 100.

I'm not sure where to start with this.

Upvotes: 1

Views: 116

Answers (1)

James_D
James_D

Reputation: 209418

The Screen API allows you to check the values you have are within the bounds of the current configuration.

E.g. to test if there is a physical graphics device that intersects the bounds saved in the configuration settings, you could do:

double x = Settings.getWindowX();
double y = Settings.getWindowY();
double h = Settings.getWindowH();
double w = Settings.getWindowW();

primaryStage.setScene(mainScene);

if (Screen.getScreensForRectangle(x, y, w, h).isEmpty()) {

    // no screen intersects saved values...
    // just center on primary screen:

    primaryStage.centerOnScreen();

} else {    

    primaryStage.setX(x);
    primaryStage.setY(y);
    primaryStage.setWidth(w);
    primaryStage.setHeight(h);

}

Upvotes: 2

Related Questions