我知道有很多关于mousePressed不能正常工作的帖子,但我还没有找到我的问题的答案。我写了一个程序,只是为了好玩和体验,但我在使用Robot类的mousePressed方法时遇到了问题。这是我的代码:
//Program to say "Hi!" by moving cursor
//https://sketch.io/sketchpad/
//Open up sketchpad, run OCursor, then click on the sketchpad
import java.awt.*;
import javax.swing.*;
import java.awt.event.InputEvent;
public class OCursor {
public static void main(String[] args) {
try {
// These are the screen coordinates
int cd1 = 400;
int cd2 = 600;
int cd3 = 700;
int cd4 = 750;
int cd5 = 800;
int cd6 = 1000;
int cd7 = 1100;
int cd8 = 1200;
int cd9 = 1400;
// This is the time and amount of steps
int t = 300, n = 5000;
// 5 second delay to click on sketchpad
Robot robot = new Robot();
robot.delay(5000);
// Move and click the cursor
robot.mouseMove(cd2, cd5);
robot.mousePress(InputEvent.BUTTON1_MASK);
mouseGlide(cd2, cd5, cd2, cd1, t, n);
mouseGlide(cd2, cd2, cd5, cd2, t, n);
mouseGlide(cd5, cd5, cd5, cd1, t, n);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(100);
Robot robot2 = new Robot();
robot2.mouseMove(cd6, cd1);
robot2.mousePress(InputEvent.BUTTON1_MASK);
mouseGlide(cd6, cd1, cd8, cd1, t, n);
mouseGlide(cd7, cd1, cd7, cd5, t, n);
mouseGlide(cd6, cd5, cd8, cd5, t, n);
robot2.mouseRelease(InputEvent.BUTTON1_MASK);
robot2.delay(100);
Robot robot3 = new Robot();
robot3.mouseMove(cd9, cd5);
robot3.mousePress(InputEvent.BUTTON1_MASK);
mouseGlide(cd9, cd5, cd9, cd4, t, n);
robot3.mouseRelease(InputEvent.BUTTON1_MASK);
robot3.delay(100);
robot3.mouseMove(cd9, cd3);
robot3.mousePress(InputEvent.BUTTON1_MASK);
mouseGlide(cd9, cd3, cd9, cd1, t, n);
robot3.mouseRelease(InputEvent.BUTTON1_MASK);
robot3.delay(100);
}
catch (AWTException err) {
err.printStackTrace();
}
}
public static void mouseGlide(int x1, int y1, int x2, int y2, int t, int n) {
// "t" being time and "n" being amount of steps, with more steps being smoother
// mouseGlide code borrowed from http://stackoverflow.com/questions/9387483/how-to-move-a-mouse-smoothly-throughout-the-screen-by-using-java
try {
Robot robot = new Robot();
double dx = (x2 - x1) / ((double) n);
double dy = (y2 - y1) / ((double) n);
double dt = t / ((double) n);
for (int step = 1; step <= n; step++) {
Thread.sleep((int) dt);
robot.mouseMove((int) (x1 + dx * step), (int) (y1 + dy * step));
}
}
catch (AWTException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}我的问题是mousePress实际上不会正确发布。它要么根本不释放,要么在应该按下的时候释放。我克服了这一点,每次需要发布mouseMove时都使用它,但这不应该是必要的。我听说在每个mouseRelease后面设置延迟应该可以解决这个问题,但它什么也没做。我不明白为什么它不能正常工作,为什么我必须使用mouseMove而不是mouseRelease。我还尝试在每个字母上使用新的机器人,但没有任何区别。
如果代码运行时在绘制的每个字母之间没有mouseMove,它将无法正常工作。
此外,我在mouseGlide中使用了其他人的代码,因为这只是我在测试Robot类,因为我从未使用过它。
发布于 2017-09-19 22:51:37
尝试使用InputEvent.BUTTON1_DOWN_MASK;。我使用mousePress和mouseRelease的方式和你一样,只有一个区别。
https://stackoverflow.com/questions/39929505
复制相似问题