如何确定哪些监控摇摆鼠标事件中出现?
-
12-09-2019 - |
题
我有一个部件上的Java的MouseListener来检测鼠标印刷机。我怎样才能知道哪些监控按下鼠标发生?
@Override
public void mousePressed(MouseEvent e) {
// I want to make something happen on the monitor the user clicked in
}
我想达到的效果是:当用户按下我的应用程序的鼠标按钮,弹出一个窗口显示一些信息,直到鼠标被释放。我想确保该窗口用户点击其中被定位,但我需要使得整个窗口是可见的调整在当前屏幕上的窗口的位置。
解决方案
您可以从 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
...
其他提示
里奇的回答帮我找到一个完整的解决方案:
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();
}
由于Java 1.6,你可以使用getLocationOnScreen,在以前的版本中,你必须得到生成该事件的组件的位置:
Point loc;
// in Java 1.6
loc = e.getLocationOnScreen();
// in Java 1.5 or previous
loc = e.getComponent().getLocationOnScreen();
您必须使用GraphicsEnvironment中类来获取绑定的屏幕。
也许e.getLocationOnScreen();将工作?这只是为Java 1.6。
不隶属于 StackOverflow