【问题标题】:Detect current screen bounds检测当前屏幕边界
【发布时间】:2012-07-30 00:42:20
【问题描述】:

我正在开发一个具有setDecoration(false)MouseMotionlistener 的应用程序,因此我可以移动它,目前我正在尝试制作一个最大化按钮。在默认显示器上它可以完美运行,但在第二台显示器上,如果我单击最大化按钮,它将最大化到默认屏幕。如何获取应用程序当前所在屏幕的 X 和 Y 坐标?

I.E.我有 2 台显示器,分辨率均为 1600x900,因此如果应用程序位于显示器 1 上,则 X 和 Y 将为 0 和 0,但如果它是第二台显示器,则为 1600 和 0。

但我需要它,以便它适用于所有尺寸的显示器,即 1200x800,或者如果显示器是垂直放置而不是水平放置。

【问题讨论】:

    标签: java swing awt screen mousemotionevent


    【解决方案1】:

    答案取决于屏幕的定义。你想要默认的屏幕边界还是特定的屏幕边界?

    我使用以下(及其变体)来确定单个屏幕的屏幕边界

    public static GraphicsDevice getGraphicsDeviceAt(Point pos) {
        GraphicsDevice device = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice lstGDs[] = ge.getScreenDevices();
        ArrayList<GraphicsDevice> lstDevices = new ArrayList<GraphicsDevice>(lstGDs.length);
    
        for (GraphicsDevice gd : lstGDs) {
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            Rectangle screenBounds = gc.getBounds();
            if (screenBounds.contains(pos)) {
                lstDevices.add(gd);
            }
        }
    
        if (lstDevices.size() == 1) {
            device = lstDevices.get(0);
        }
        return device;
    }
    
    public static Rectangle getScreenBoundsAt(Point pos) {
        GraphicsDevice gd = getGraphicsDeviceAt(pos);
        Rectangle bounds = null;
    
        if (gd != null) {
            bounds = gd.getDefaultConfiguration().getBounds();
        }
        return bounds;
    }
    

    基本思想是提供一个屏幕位置并找到与之匹配的屏幕。我有一些变化,可以选择 ComponentWindow,但本质上归结为这一点。

    MouseEvent,您可以通过调用MouseEvent.getLocationOnScreen 来简单地获取屏幕坐标

    现在,从你的问题来看,听起来你想知道整个“虚拟”屏幕边界(我可能错了),但我使用这种方法(实际上我用它来动态创建多显示器壁纸,但这是另一个问题)

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

    基本上,它只是遍历所有屏幕设备并将那里的区域添加在一起以形成一个“虚拟”矩形。您可以使用相同的概念将每个屏幕设备的边界作为数组返回。

    【讨论】:

      【解决方案2】:

      您可以使用它来获取屏幕尺寸。

      Toolkit toolkit =  Toolkit.getDefaultToolkit ();
      Dimension dim = toolkit.getScreenSize();
      System.out.println("Width of Screen Size is "+dim.width+" pixels");
      System.out.println("Height of Screen Size is "+dim.height+" pixels");
      

      【讨论】:

      • 这将只返回“默认”屏幕边界
      • 我想要的主要是获取应用程序当前所在屏幕的左上角坐标,所以从我的设置来看,它可能是 0、0 或 1600、0,如我有 2 台显示器并排在 1600x900,但如果我的显示器一个在另一个顶部,左边将是 0、0 或 0、900,你知道我要去哪里吗?...
      猜你喜欢
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 2022-01-17
      • 2011-06-05
      • 1970-01-01
      • 2013-05-25
      相关资源
      最近更新 更多