检测当前屏幕边界

时间:2012-07-30 00:42:20

标签: java swing awt screen mousemotionevent

我正在处理一个setDecoration(false)我有一个MouseMotionlistener的应用程序,所以我可以移动它,此刻我正在尝试制作一个最大化按钮。在默认监视器上它可以很好地工作,但在第二个监视器上,如果我单击最大化按钮,它将最大化到默认屏幕。我怎样才能得到X&应用程序当前所在屏幕的Y坐标?

即。我有两台1600x900的显示器,所以如果应用程序在显示器1上,那么X& Y将是0& 0,但如果它是第二个监视器,它将是1600& 0

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

2 个答案:

答案 0 :(得分:4)

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

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

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

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

答案 1 :(得分:0)

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

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");