我正在使用 Java 进行一些 Swing GUI 工作,我认为我的问题相当简单;如何设置鼠标的位置?
正如其他人所说,这可以通过使用来实现Robot.mouseMove(x,y) http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#mouseMove%28int,%20int%29。然而,在多显示器情况下工作时,此解决方案会出现问题,因为机器人使用主屏幕的坐标系工作,除非您另行指定。
这是一个允许您传递任何基于点的全局屏幕坐标的解决方案:
public void moveMouse(Point p) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
// Search the devices for the one that draws the specified point.
for (GraphicsDevice device: gs) {
GraphicsConfiguration[] configurations =
device.getConfigurations();
for (GraphicsConfiguration config: configurations) {
Rectangle bounds = config.getBounds();
if(bounds.contains(p)) {
// Set point to screen coordinates.
Point b = bounds.getLocation();
Point s = new Point(p.x - b.x, p.y - b.y);
try {
Robot r = new Robot(device);
r.mouseMove(s.x, s.y);
} catch (AWTException e) {
e.printStackTrace();
}
return;
}
}
}
// Couldn't move to the point, it may be off screen.
return;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)