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

kli*_*009 2 java graphics swing jframe

我的应用程序用于多屏幕环境。应用程序在收盘时存储它的位置并从最后一个位置开始。
我通过调用获取位置frame.getLocation() 如果框架在主屏幕上或者它在主屏幕的右侧,这会给我一个正值。位于主屏幕左侧的屏幕上的帧获得 X
的负值。当屏幕配置更改时(例如,多个用户共享一个 Citrix 帐户并具有不同的屏幕分辨率),问题就会出现。

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

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

现在,根据屏幕的顺序(辅助监视器放置在主监视器的左侧还是右侧),框架可能是可见的,或者不是。

你能告诉我如何解决这个问题吗?

非常感谢

Mad*_*mer 6

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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


Joh*_*ohn 5

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

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

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;
}
Run Code Online (Sandbox Code Playgroud)