2009-08-08 75 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

相关问题