How to mouse click on any java component without a

2019-07-27 03:48发布

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.

1条回答
Summer. ? 凉城
2楼-- · 2019-07-27 04:22

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);
}
查看更多
登录 后发表回答