Anju Maaka
Anju Maaka

Reputation: 274

Finding if a location exists on any available screen (Java)

I use a small (self-made) Java application on my laptop. This app remembers the location on screen where it was last open and opens there the next time I start it.

This causes an issue in one specific case; sometimes I use one screen (while working remotely, because COVID) and sometimes I use two (when at the office). The place I want the frame when using two screens is on my secondary screen, which makes the app start up outside of the screen whenever I use only one screen.

Is there any way to check if a location is "on screen" or not? I want to be able to check if the frame is on any available screen, so I can move it to one if it's not. Anyone know how to do this, preferably without having to import any external library?

Upvotes: 0

Views: 128

Answers (1)

Daniel
Daniel

Reputation: 113

What you can do is get a monitor boundries and check if the location is within the boundries of the screen, and iterate all the monitors list, if it was not in any monitor then you can set the location of window back to the main screen, you can use this code to get connected monitors:

 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
 GraphicsDevice[] devices = ge.getScreenDevices();

By this you can make a method to see if it's on the a specific screen or not:

 public static boolean isVisibleOnScreen(int locX, int locY, int screenIndex) {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] devices = ge.getScreenDevices();
    // Check if there index is valid
    if (screenIndex > -1 && screenIndex < devices.length) {
        Rectangle bounds = devices[screenIndex].getDefaultConfiguration().getBounds();
        // Check if within screen boundries
        if (bounds.contains(locX, locY)) {
            return true;
        }
    }
    return false;
}

Upvotes: 0

Related Questions