tags:

views:

111

answers:

2

Hello,

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!

+2  A: 

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.

Joel
+1  A: 

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.

Generic Prodigy