Brade Brade - 6 months ago 15
Java Question

Java robot doesn't work

I was writing code which first adds mouse position to arraylist (with dealys) and after that, it will repeat by moveMouse (robot). I think that I'm doing all well. But it's not working. Can anyone help me? Thanks!

Code:
CoursorMove

public class CoursorMove {

private ArrayList<Point> coordinates = new ArrayList<>();

public void addNewObjectWithCoordinates() {
coordinates.add(MouseInfo.getPointerInfo().getLocation());
}

public Point getCoordinate(int index) {
return coordinates.get(index);

}

public void play() {

for (int i = 0; i < 5; i++) {
CoursorMove bang = new CoursorMove();
bang.addNewObjectWithCoordinates();
System.out.println(bang.getCoordinate(0).getX());

try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

int howmany = coordinates.size();
int index = 0;

public int getHowmany() {
return howmany;
}

public void setHowmany(int howmany) {
this.howmany = howmany;
}

public void moveCoursor() {

while (index < howmany) {
try {
Robot robot = new Robot();
robot.mouseMove(coordinates.get(index).x, coordinates.get(index).y);
robot.delay(1500);
} catch (AWTException e) {
System.err.println("Error CM 68L"); // error CoursorMove class
// Line 68
e.printStackTrace();
}
index++;
}
}
}


Main.

public class Main {
public static void main(String[] args) {
CoursorMove triup = new CoursorMove();
triup.play();
triup.moveCoursor();
}
}

Answer

Here are a few modifications that should help.

First, you don't need to store separate variables for how many coordinates you have

public int getHowmany() {
    return coordinates.size();
}

Second, you are never adding to the same coordinates list because you use a new instance of your class. You don't need to make one at all, you can call those methods directly on the current instance.

public void play() {

    for (int i = 0; i < 5; i++) {
        addNewObjectWithCoordinates();
        System.out.println(getCoordinate(0).getX());

        // sleep thread 
    }
}

Then same problem below, you probably only want one robot, not one for every loop

public void moveCoursor() {

    Robot robot = new Robot();
    while (index < howmany) {
        try {
            robot.mouseMove...