我正在用Java做一些Swing GUI工作,我想我的问题相当简单;如何设置鼠标的位置?
发布于 2012-05-19 20:42:16
正如其他人所说,这可以使用Robot.mouseMove(x,y)
来实现。但是,此解决方案在多显示器情况下工作时会出现问题,因为机器人使用主屏幕的坐标系工作,除非您另行指定。
这是一个允许你传递任何基于全局屏幕坐标的点的解决方案:
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;
}
发布于 2010-05-31 12:34:54
发布于 2010-05-31 12:14:11
查看Robot类。
https://stackoverflow.com/questions/2941324
复制相似问题