获取辅助监视器的大小

时间:2015-04-27 22:44:26

标签: java swing screen multiple-monitors

我似乎很难在Java中获得多个监视器的大小;

所以我做了一个应该显示屏幕尺寸的小窗口,它适用于我的主显示器,现在我希望能够确定它所在的显示器的大小,我使用getLocation()要知道我的JFrame在哪里,但我不知道如何获得该监视器的大小,我只能得到主要的,甚至他们的总大小。

1 个答案:

答案 0 :(得分:2)

您需要深入GraphicsEnvironment,这样您就可以访问系统上提供的所有GraphicsDevice

基本上从那里开始,你需要遍历每个GraphicsDevice并测试窗口是否在给定GraphicsDevice

的范围内

有趣的部分是,如果窗口跨越多个屏幕,该怎么办......

public static GraphicsDevice getGraphicsDevice(Component comp) {

    GraphicsDevice device = null;
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice lstGDs[] = ge.getScreenDevices();
    ArrayList<GraphicsDevice> lstDevices = new ArrayList<GraphicsDevice>(lstGDs.length);

    if (comp != null && comp.isVisible()) {
        Rectangle parentBounds = comp.getBounds();
        /*
         * If the component is not a window, we need to find its location on the
         * screen...
         */
        if (!(comp instanceof Window)) {
            Point p = new Point(0, 0);
            SwingUtilities.convertPointToScreen(p, comp);
            parentBounds.setLocation(p);
        }

        // Get all the devices which the window intersects (ie the window might expand across multiple screens)
        for (GraphicsDevice gd : lstGDs) {
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            Rectangle screenBounds = gc.getBounds();
            if (screenBounds.intersects(parentBounds)) {
                lstDevices.add(gd);
            }
        }

        // If there is only one device listed, return it...
        // Otherwise, if there is more then one device, find the device
        // which the window is "mostly" on
        if (lstDevices.size() == 1) {
            device = lstDevices.get(0);
        } else if (lstDevices.size() > 1) {
            GraphicsDevice gdMost = null;
            float maxArea = 0;
            for (GraphicsDevice gd : lstDevices) {
                int width = 0;
                int height = 0;
                GraphicsConfiguration gc = gd.getDefaultConfiguration();
                Rectangle bounds = gc.getBounds();
                Rectangle2D intBounds = bounds.createIntersection(parentBounds);
                float perArea = (float) ((intBounds.getWidth() * intBounds.getHeight()) / (parentBounds.width * parentBounds.height));
                if (perArea > maxArea) {
                    maxArea = perArea;
                    gdMost = gd;
                }
            }

            if (gdMost != null) {
                device = gdMost;
            }
        }
    }

    return device;
}