2015-04-27 58 views
0

我似乎很難在Java中獲得多個監視器的大小;獲取輔助監視器的大小

因此,我做了一個小窗口,應該顯示一個屏幕的尺寸,它適用於我的主監視器,現在我想能夠確定它的監視器的大小,我用getLocation()知道在哪裏我的JFrame是,但我不知道如何獲得該顯示器的大小,我只能得到主顯示器的大小,甚至是他們的總大小。

+0

請在發佈問題之前養成堆棧溢出的現有答案。你之前詢問過的問題很有可能出現在你面前。 – MarsAtomic

回答

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; 
} 
相關問題