How do I lock the mouse inside a JFrame
I would like to lock the mouse inside a JFrame. That is, the mouse can not leave the contents of the JFrame (unless the user hits escape, alt-tab,开发者_运维问答 or the window otherwise looses focus). Ideas?
Thanks!
I'm not sure if there's a more automatic way of doing that, but you could use the Robot class to set the mouse position. So in the event handler for when the JFrame gains focus you can start watching the mouse move event, and when the mouse moves just make sure it stays within the JFrame. If it leaves the JFrame you can use the Robot class to set the mouse's position to go back.
Then when the window loses focus, you can unregister from the mouse move event.
The Robot class is ideal for this type of thing, but I would suggest another approach.
Perhaps making the game full screen (maximizing the window pane) would achieve what you want instead. The mouse would be unable to exit the window and no ugly Robot-esque hack needs to be used to force the user to stay within the borders.
Another workaround I just thought of - lock the cursor to the centre of the Frame, and make it invisible.Then render a software cursor where the real cursor should be. You can then lock the cursor to whatever area you want.
Here's a sneaky one could work if you don't use mouse button 2 in your game. Use a Robot to press down BUTTON2.
The idea is so the mouse gets dragged, not moved. Whenever you get a mouse moved event, it's because the user has released button2, so press it down again.
Whenever you get a mouse dragged event, if the mouse is outside the window, put it back in.
精彩评论