3

Currently to simulate mouse clicks in my application I use the Robot class of Java. It seems to use the desktop as bounds/grid for knowing where the Point maps out to on the screen.

Example:

Robot bot = new Robot();
bot.mouseMove(1099,22); //Manually collected point..
bot.delay(100);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);

Goal:

Robot forces my mouse/cursor to be used, I want to be able to do other things on my computer while this code runs doing clicks on only my Java application where I have programmed it to.

Is there a way to do this with JNA? Am not concerned to supporting any Operating System other then windows but still needs to be a Java application due to legacy technologies.

Hesein Burg
  • 329
  • 3
  • 13

1 Answers1

5

The following code clicks on the target Component at (x, y) relative to target.

private static void click(Component target, int x, int y)
{
   MouseEvent press, release, click;
   Point point;
   long time;

   point = new Point(x, y);

   SwingUtilities.convertPointToScreen(point, target);

   time    = System.currentTimeMillis();
   press   = new MouseEvent(target, MouseEvent.MOUSE_PRESSED,  time, 0, x, y, point.x, point.y, 1, false, MouseEvent.BUTTON1);
   release = new MouseEvent(target, MouseEvent.MOUSE_RELEASED, time, 0, x, y, point.x, point.y, 1, false, MouseEvent.BUTTON1);
   click   = new MouseEvent(target, MouseEvent.MOUSE_CLICKED,  time, 0, x, y, point.x, point.y, 1, false, MouseEvent.BUTTON1);

   target.dispatchEvent(press);
   target.dispatchEvent(release);
   target.dispatchEvent(click);
}
Nathan
  • 8,093
  • 8
  • 50
  • 76
  • Nice code. Does this use the an emulated mouse and not the operating systems mouse? – Hesein Burg Oct 21 '17 at 14:50
  • The operating system is not involved with this code. This code emulates the exact same events that an actual physical mouse would do if a user clicked it. In other words, the Java program can not easily tell the difference between the above code and an actual physical mouse. – Nathan Oct 21 '17 at 15:57
  • You can use the shorter MouseEvent constructor without the location-on-screen (it's calculated automatically). Nice code otherwise. – Stefan Reich Dec 14 '18 at 19:03