1

我想确定 aJFrame在其屏幕上的位置。当我使用getLocationOnScreen()或者getLocation()我只是得到w1+p但我想确定只是p.

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

使用getGraphicsConfiguration().getDevice().getDisplayMode().getWidth()返回w2很好,但我无法确定JFrames活动屏幕上的位置。

我的总体目标是确保JFrame永远不会有超出可见屏幕区域的区域。例如,如果将JFrame其从屏幕#2 的可见区域向上移动 100 像素,则将其向下移动 100 像素进行校正。

如何获得 aJFrame在其活动屏幕上的位置或以任何其他方式确保完整JFrame可见(假设`JFrame.size <= Screen.size)?

4

1 回答 1

0

我自己找到了一个解决方案并将其记录在我的网站上。简而言之,这段代码对我有用:

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

如果有人知道更简单的解决方案,请告诉我:)

于 2014-04-23T19:15:27.150 回答