3

I am trying to simulate real mouse clicks without moving the cursor with javas robot class. Is it possible putting this code in a while-loop or something to register the mouse position, and move the mouse to that position after the actual click? so far the code is told to move the mouse to the registered mouse position (it registers once I run the code) but I want it to move the mouse to the same position as my mouse is on, not somewhere in the corner. Thank you.

 while(true) { PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int xOrig = (int)b.getX(); int yOrig = (int)b.getY(); try { Robot r = new Robot(); Thread.sleep(3000); r.mouseMove(720, 360); r.mousePress(InputEvent.BUTTON1_MASK); //press the left mouse button r.mouseRelease(InputEvent.BUTTON1_MASK); //release the left mouse button //move the mouse back to the original position r.mouseMove(xOrig, yOrig); } catch (Exception e) { System.out.println(e.toString()); } } } 

}

1 Answer 1

1

Just put the Thread.sleep(3000) at the end of the try{ } block.

Your current code fetches the new "original position" right after it moves the mouse to the old original position

Without the loop

public static void main(String[] args) throws InterruptedException { //For testing Thread.sleep(1000); PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int xOrig = (int) b.getX(); int yOrig = (int) b.getY(); try { Robot r = new Robot(); r.mouseMove(720, 360); // press the left mouse button r.mousePress(InputEvent.BUTTON1_MASK); // release the left mouse button r.mouseRelease(InputEvent.BUTTON1_MASK); // move the mouse back to the original position r.mouseMove(xOrig, yOrig); Thread.sleep(3000); } catch (Exception e) { System.out.println(e.toString()); } } 
Sign up to request clarification or add additional context in comments.

3 Comments

By the way, how do I close the loop so that it only perform the mouse click once? I can't seem to get it work with the }s
Ehm. Either you have a loop or you perform it once. Just remove the while(true){ ... }
Yes I know but if I remove the while-loop the mouse will move to a corner after the actual click. I want it to stay at the exact same position as the mouse is at

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.