2009-08-08 37 views
10

我在組件上有一個Java MouseListener來檢測鼠標按下。我怎麼知道鼠標按鍵發生在哪個監視器上?如何確定哪個監視器發生Swing鼠標事件?

@Override 
public void mousePressed(MouseEvent e) { 
    // I want to make something happen on the monitor the user clicked in 
} 

我想要達到的效果是:當用戶在我的應用程序上按下鼠標按鍵,彈出一個窗口顯示一些信息,直到鼠標被釋放。我想確保此窗口位於用戶點擊的位置,但我需要調整當前屏幕上的窗口位置,以便可以看到整個窗口。

+0

我不知道,就是這麼簡單。我認爲你必須捕捉鼠標才能看到窗外的任何點擊,並且我不知道如何在java中做到這一點(因此,評論 - 我沒有「答案」)。 – 2009-08-08 09:16:48

+1

比爾,你是對的,這並不容易。這就是爲什麼我問集體大腦是堆棧溢出! – 2009-08-08 13:22:17

回答

13

您可以從java.awt.GraphicsEnvironment獲取顯示信息。您可以使用它獲取有關您本地系統的信息。包括每臺顯示器的邊界。

Point point = event.getPoint(); 

GraphicsEnvironment e 
    = GraphicsEnvironment.getLocalGraphicsEnvironment(); 

GraphicsDevice[] devices = e.getScreenDevices(); 

Rectangle displayBounds = null; 

//now get the configurations for each device 
for (GraphicsDevice device: devices) { 

    GraphicsConfiguration[] configurations = 
     device.getConfigurations(); 
    for (GraphicsConfiguration config: configurations) { 
     Rectangle gcBounds = config.getBounds(); 

     if(gcBounds.contains(point)) { 
      displayBounds = gcBounds; 
     } 
    } 
} 

if(displayBounds == null) { 
    //not found, get the bounds for the default display 
    GraphicsDevice device = e.getDefaultScreenDevice(); 

    displayBounds =device.getDefaultConfiguration().getBounds(); 
} 
//do something with the bounds 
... 
+0

這是解決方案的一半,它幫助我解決了整個解決方案。謝謝! – 2009-08-08 13:18:28

+0

這是,我投票給你! – 2009-08-08 13:57:39

0

也許e.getLocationOnScreen();將工作?它僅適用於java 1.6。

1

由於Java 1.6,你可以使用getLocationOnScreen,在以前的版本中,你必須得到該組件的生成該事件的位置:

Point loc; 
// in Java 1.6 
loc = e.getLocationOnScreen(); 
// in Java 1.5 or previous 
loc = e.getComponent().getLocationOnScreen(); 

你將不得不使用GraphicsEnvironment中類來獲取綁定的畫面。

2

豐富的回答幫我找到一個完整的解決方案:

public void mousePressed(MouseEvent e) { 
    final Point p = e.getPoint(); 
    SwingUtilities.convertPointToScreen(p, e.getComponent()); 
    Rectangle bounds = getBoundsForPoint(p); 
    // now bounds contains the bounds for the monitor in which mouse pressed occurred 
    // ... do more stuff here 
} 


private static Rectangle getBoundsForPoint(Point point) { 
    for (GraphicsDevice device : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) { 
     for (GraphicsConfiguration config : device.getConfigurations()) { 
      final Rectangle gcBounds = config.getBounds(); 
      if (gcBounds.contains(point)) { 
       return gcBounds; 
      } 
     } 
    } 
    // if point is outside all monitors, default to default monitor 
    return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); 
} 
+0

如果您想獲得默認監視器,請參閱我的更新答案,在Windows應該居中顯示在所有顯示器上的多屏幕系統上,getMaximumWindowBounds()返回*整個*顯示區域的邊界。 – 2009-08-08 14:19:25

相關問題