Issue
I have a javafx game which by the way is running as a windowed app. The game is controlled by moving and clicking the mouse but my problem occurs when I move the mouse too far and it goes outside the window, since as I mentioned clicking is also part of the game, and we all know what happens when you click the program that is behind your windowed app, say if I click google chrome by accident, and my game is then hidden behind google chrome, but since it's still running I lose unless I am able to alt+tab quick enough back into the game.
I wish to solve this problem by not allowing the mouse to exit the window, constraining it to the boundaries of the window/stage/scene that my game is running in.
Is it possible to constrict the mouse like this? How should I do so?
Solution
It's possible to do this via Robot. Specifically, you can use mouseMove
to reset the mouse position when it strays too far.
Alternatively, you might consider instead allowing the user to escape your window, but let your game react to that event. For example, pausing the game when the mouse leaves the window.
You can use pointerInfo
to track the position of the cursor (as discussed here).
Answered By - mcmahoniel