Ben*_*key 18 java mouse user-interface swing
我正在使用Java进行一些Swing GUI工作,我认为我的问题相当简单; 如何设置鼠标的位置?
Dan*_*iel 22
正如其他人所说,这可以通过使用来实现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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29976 次 |
| 最近记录: |