Hesein Burg
Hesein Burg

Reputation: 329

How to mouse click on any java component without actual mouse being overridden

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.

Upvotes: 3

Views: 3085

Answers (1)

Nathan
Nathan

Reputation: 8940

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);
}

Upvotes: 5

Related Questions