开发者

Listeners in conjunction with Robot class

I've been playing with the Robot class recently and I have it doing 开发者_运维知识库what I want, but I haven't figured out how to interrupt/stop its actions via user input.

For example: I want it to click the desktop a hundred times but I decide forty clicks in that I want to make it quit (or pause).

I'd like to be able to do something simple like press a certain key or press the middle mouse button in order to tell it to stop. In order to do this, it must be able to listen for input outside of the Java application, since the actions the Robot is performing are in other programs.


As edward said, there doesn't seem to be a way to do exactly what I was looking for. So this answer is to explain how I achieved an acceptable substitute.

The other question edward linked to had stated that

MouseInfo.getPointerInfo().getLocation()

is capable of fetching the mouse coordinates regardless of what the mouse is doing. My program uses the robot class to control the mouse within a specific range of coordinates. I also wanted to be able to disable the program via user input.

To achieve this result, I compared the x and y coordinates of the mouse to the x and y coordinates that the robot last set it to. If the two do not match, the program exits.

Pausing the program by this method would be impractical because resuming would require going back to the original x and y coordinate prior to pausing, but it does at least give an example of how to achieve stopping without actually being focused on the java parent program.

In order to pause the program, you would instead compare the coordinates to a range of coordinates (have the coordinates create an imaginary, 2D box). If the mouse's coordinates are within that range: pause. To resume, do the opposite check (mouse not being in that range).


You may be able to use some of the code from this answer: Simulate a key held down in Java

And then add a Listener to whatever action, component, whatever to call the stop method on the robot command.

Does that provide you with some inspiration?


Edit After further discussion the real question is:

How to respond to external Mouse Events (Outside the Java Application) inside a Java application?

It Seems that you can't without native code and Mouse Hooks as it's OS Dependent.

For Further Discussion see Is it possible to have a MouseMotionListener listen to all system mouse motion events?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜