有没有办法在Java中模拟鼠标拖动事件。我可以使用java.awt.Robot模拟鼠标点击和鼠标移动。但是,我不能模拟鼠标拖动的动作。
我尝试让robot类使用robot.mousePress()按住鼠标按钮,并在调用robot.mouseRelase之前,在鼠标移动期间暂停几次,同时移动鼠标位置。但是,所有这些操作都是模拟鼠标光标移动,而不是模拟鼠标拖动事件。
我将包含我正在使用的代码片段;但是,它所做的一切都是我在上面提到的,单击鼠标并移动鼠标光标。
我在Windows 7上运行此应用程序。
提前谢谢。
public void click() throws AWTException, InterruptedException {
int numberOfMoveIterations = 15;
Robot bot = new Robot();
Thread.sleep(mouseDownDelayClickTime + this.delayTime);
bot.mouseMove((int) (mouseClickDownXLocation * this.widthEventOffset), (int) (mouseClickDownYLocation * this.heightEventOffset));
bot.mousePress(InputEvent.BUTTON1_MASK);
if (mouseClickDownXLocation != mouseClickUpXLocation || mouseClickDownYLocation != mouseClickUpYLocation) {
int xAmountToMove = mouseClickUpXLocation - mouseClickDownXLocation;
int yAmountToMove = mouseClickUpYLocation - mouseClickDownYLocation;
int xAmountPerIteration = xAmountToMove / numberOfMoveIterations;
int yAmountPerIteration = yAmountToMove / numberOfMoveIterations;
int currentXLocation = mouseClickDownXLocation;
int currentYLocation = mouseClickDownYLocation;
while (currentXLocation < mouseClickUpXLocation + xAmountToMove
&& currentYLocation < mouseClickUpYLocation + yAmountToMove) {
currentXLocation += xAmountPerIteration;
currentYLocation += yAmountPerIteration;
bot.mouseMove(currentXLocation, currentYLocation);
Thread.sleep(mouseUpDelayClickTime);
}
}
bot.mouseRelease(InputEvent.BUTTON1_MASK);}
发布于 2017-07-13 00:42:48
我遇到了和以前类似的问题。下面是我回答的另一个问题的链接:https://stackoverflow.com/a/45063135/
添加thread.sleep();是制作拖动运动的正确解决方案。但是你把它添加到了错误的位置。您需要确保在按下鼠标时光标正在移动。为了挂起线程mousePressed,您必须在mousePressed和mouseMoved之间添加thread.sleep。
代码如下:
public void click() throws AWTException, InterruptedException {
int numberOfMoveIterations = 15;
Robot bot = new Robot();
thread.sleep(mouseDownDelayClickTime + this.delayTime);
bot.mouseMove((int) (mouseClickDownXLocation * this.widthEventOffset), (int) (mouseClickDownYLocation * this.heightEventOffset));
bot.mousePress(InputEvent.BUTTON1_MASK);
/* suspend the current thread here */
thread.sleep(mouse pressed thread suspended time);
if (mouseClickDownXLocation != mouseClickUpXLocation || mouseClickDownYLocation != mouseClickUpYLocation) {
int xAmountToMove = mouseClickUpXLocation - mouseClickDownXLocation;
int yAmountToMove = mouseClickUpYLocation - mouseClickDownYLocation;
int xAmountPerIteration = xAmountToMove / numberOfMoveIterations;
int yAmountPerIteration = yAmountToMove / numberOfMoveIterations;
int currentXLocation = mouseClickDownXLocation;
int currentYLocation = mouseClickDownYLocation;
while (currentXLocation < mouseClickUpXLocation + xAmountToMove
&& currentYLocation < mouseClickUpYLocation + yAmountToMove) {
currentXLocation += xAmountPerIteration;
currentYLocation += yAmountPerIteration;
bot.mouseMove(currentXLocation, currentYLocation);
}
}
bot.mouseRelease(InputEvent.BUTTON1_MASK);https://stackoverflow.com/questions/43617692
复制相似问题