我正在编写一个应用程序,它将教授使用计算机的基础知识,我需要移动鼠标来显示您必须执行的操作。我试过这个:
public static void click(Point p) throws AWTException{
Robot r = new Robot();
r.mouseMove(p.x, p.y);
r.mousePress(InputEvent.BUTTON1_MASK);
try { Thread.sleep(100); } catch (Exception e) {}
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
一切正常,但鼠标会传送到指定的坐标,而不会移动。所以我的问题是:如何有效地模拟鼠标的移动,单击左右和拖放(就像你按住鼠标按钮)
答案 0 :(得分:0)
public static void click(Point p) throws AWTException{
Robot r = new Robot();
gradualMouseMove(p, r);
r.mousePress(InputEvent.BUTTON1_MASK);
try { Thread.sleep(100); } catch (Exception e) {}
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
private static void gradualMouseMove(Point pointIn, Robot robot) throws InterruptedException {
//TO ADJUST SPEED OF MOVEMENT
//CHANGE: 1:sleep duration 2:deltaX # 3:deltaY #
Point mouseLocation; //Point for updating the currentLocation
int deltaX; //X coordinate update value
int deltaY; //Y coordinate update value
boolean xInProgess = true; //Stop condition for X
boolean yInProgess = true; //Stop condition for Y
do{
//update Mouse Location
mouseLocation = MouseInfo.getPointerInfo().getLocation();
//calculate X coordinates
if(pointIn.getX() - mouseLocation.getX() > 2){
deltaX = 1; //Mouse is LEFT of Destination
}else if (pointIn.getX() - mouseLocation.getX() < -2){
deltaX = -1; //Mouse is RIGHT of Destination
}else{
xInProgess = false; //X Done
deltaX = 0;
}
//calculate Y coordinates
if(pointIn.getY() - mouseLocation.getY() > 2){
deltaY = 1; //Mouse is ABOVE Destination
}else if (pointIn.getY() - mouseLocation.getY() < -2){
deltaY = -1; //Mouse is BELOW Destination
}else{
yInProgess = false; //Y Done
deltaY = 0;
}
//move mouse on Screen by adjustment amount
robot.mouseMove((int)(mouseLocation.getX()+deltaX), (int)(mouseLocation.getY()+deltaY));
Thread.sleep(6); //pause to slow down movement
}while(xInProgess || yInProgess); //loop until complete on X & Y
}
上述方法gradualMouseMove是&#34; SLIDING&#34;的简单版本。鼠标到目的地点。
*****请注意不要在屏幕上使用点。如果鼠标永远不会到达那里,我可以防止循环退出。如果这是一个问题,您可以添加一个以特定值结束的计数。******
**加法 - 你可以在那里添加一些数学,如果你愿意,可以直接到达目的地。 (而不是目前的高原)**
但是这应该会给你一个发射台。