How do I lock the mouse inside a JFrame

淺唱寂寞╮ 提交于 2020-01-15 12:25:51

问题


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!


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2543065/how-do-i-lock-the-mouse-inside-a-jframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!