1

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.

Zephyr
  • 9,885
  • 4
  • 28
  • 63
  • Minor nitpick: it's "ensure" not "insure" – Travis Dec 13 '16 at 04:06
  • I always get those mixed up. Thanks for taking the time to point it out :) It's been corrected. – Zephyr Dec 13 '16 at 04:08
  • @Travis That's only really true in British English, I think; in US English ["insure"](https://en.wiktionary.org/wiki/insure) (also [here](https://www.merriam-webster.com/dictionary/insure)) is considered a valid alternative spelling of "ensure" (though I actually dislike "insure" in this sense). – James_D Dec 13 '16 at 04:24

1 Answers1

2

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);

}
James_D
  • 201,275
  • 16
  • 291
  • 322