Question

I want to determine the position of a JFrame on its screen. When i use getLocationOnScreen() or getLocation() i just get w1 + p but i want to determine just p.

______________   __________
|            |   | p  ____|     
|            |   |<-> |__||
|____________|   |________|
<---  w1  --->   <-- w2 -->

Using getGraphicsConfiguration().getDevice().getDisplayMode().getWidth() returns w2 whats fine, but i'm not able to determine the JFrames position on the active screen.

My overall target is to ensure that the JFrame never has an area out of the visible screen area. E.g. if the JFrame is moved 100px up out of the visible area of screen #2 its corrected with moving it down for 100px.

How can i get the position of a JFrame on its active screen or make sure in any other way that the complete JFrame is visible (asuming `JFrame.size <= Screen.size)?

Was it helpful?

Solution

I found a solution myself and document it on my website. In short, this code works for me:

public void moveToVisible(JFrame frame) {
    // Vertical position
    GraphicsDevice activeScreen = getGraphicsConfiguration().getDevice();
    if (frame.getLocation().y < 0) {
        frame.setLocation(getLocation().x, 0);
    }
    if ((frame.getLocation().y + frame.getHeight()) > 
            activeScreen.getDisplayMode().getHeight()) {
        frame.setLocation(
                frame.getLocation().x,
                (activeScreen.getDisplayMode().getHeight() 
                 - frame.getHeight())
        );
    }
    // Horizontal position
    int offsetRight = frame.getX() + frame.getWidth() - frame.getGraphicsConfiguration().getBounds().x + frame.getGraphicsConfiguration().getBounds().width;
    if (offsetRight > 0) {
        setLocation(frame.getX() - offsetRight, frame.getY());
    }
    int offsetLeft = frame.getX() - frame.getGraphicsConfiguration().getBounds().x;
    if (offsetLeft < 0) {
        frame.setLocation(frame.getX() - offsetLeft, frame.getY());
    }
}

If someone knows a more easier solution let me know :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top