如何在没有覆盖实际鼠标的情况下在任何Java组件上单击鼠标 [英] How to mouse click on any java component without actual mouse being overridden
问题描述
当前,为了模拟我的应用程序中的鼠标单击,我使用Java的Robot类.似乎使用桌面作为边界/网格来了解Point在屏幕上的映射位置.
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.
示例:
Robot bot = new Robot();
bot.mouseMove(1099,22); //Manually collected point..
bot.delay(100);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
目标:
机器人强制使用鼠标/光标,我希望能够在我的计算机上执行其他操作,而此代码仅在对其进行编程的Java应用程序上单击即可运行.
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.
是否可以使用JNA做到这一点?除了Windows之外,不关心是否支持其他任何操作系统,但是由于遗留技术的缘故,仍需要成为Java应用程序.
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.
推荐答案
以下代码单击相对于target
的(x,y)处的target
组件.
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);
}
这篇关于如何在没有覆盖实际鼠标的情况下在任何Java组件上单击鼠标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!