如何知道JFrame是否在多屏幕环境中显示在屏幕上

时间:2013-08-21 07:10:05

标签: java swing graphics jframe

我的应用程序用于多屏幕环境。应用程序将其位置关闭并从最后一个位置开始 我通过致电frame.getLocation()来获得该职位 如果框架在主屏幕上或者在主屏幕的右侧,这给了我一个正值。位于主屏幕左侧屏幕上的帧获得X的负值 当屏幕配置发生更改时(例如,多个用户共享一个Citrix帐户并具有不同的屏幕分辨率),问题就出现了。

我现在的问题是确定存储的位置是否在屏幕上可见。根据其他一些帖子,我应该使用GraphicsEnvironment来获取可用屏幕的大小,但我无法获得不同屏幕的位置。

示例:getLocation()提供Point(-250,10)
GraphicsEnvironment给出了 Device1-Width:1920
Device2-Width:1280

现在,根据屏幕的顺序(辅助显示器位于主显示器的左侧或右侧),框架可能是可见的,也可能不是。
你能告诉我如何解决这个问题吗?

非常感谢

2 个答案:

答案 0 :(得分:3)

这是一个小小的缩减,但是,如果您只想知道框架是否在屏幕上可见,您可以计算桌面的“虚拟”边界并进行测试以查看框架是否包含在其中。

public class ScreenCheck {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setBounds(-200, -200, 200, 200);
        Rectangle virtualBounds = getVirtualBounds();

        System.out.println(virtualBounds.contains(frame.getBounds()));

    }

    public static Rectangle getVirtualBounds() {
        Rectangle bounds = new Rectangle(0, 0, 0, 0);
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice lstGDs[] = ge.getScreenDevices();
        for (GraphicsDevice gd : lstGDs) {
            bounds.add(gd.getDefaultConfiguration().getBounds());
        }
        return bounds;
    }
}

现在,这会使用框架的Rectangle,但您可以使用它的位置。

同样,您可以单独使用每个GraphicsDevice并依次检查每个{...}

答案 1 :(得分:2)

这可能对寻找类似解决方案的其他人有所帮助。

我想知道我的挥杆应用程序位置的任何部分是否在屏幕外。此方法计算应用程序的区域并确定是否所有区域都可见,即使它在多个屏幕上分割。帮助您保存应用程序位置,然后重新启动它,并且显示配置不同。

public static boolean isClipped(Rectangle rec) {

    boolean isClipped = false;
    int recArea = rec.width * rec.height;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice sd[] = ge.getScreenDevices();
    Rectangle bounds;
    int boundsArea = 0;

    for (GraphicsDevice gd : sd) {
        bounds = gd.getDefaultConfiguration().getBounds();
        if (bounds.intersects(rec)) {
            bounds = bounds.intersection(rec);
            boundsArea = boundsArea + (bounds.width * bounds.height);
        }
    }
    if (boundsArea != recArea) {
        isClipped = true;
    }
    return isClipped;
}