2

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Chexxor
  • 406
  • 6
  • 17
  • 1
    http://stackoverflow.com/questions/2941324/how-do-i-set-the-position-of-the-mouse-in-java Move it to the border when the user tries moving it out. – Sarvadi Mar 28 '16 at 00:41

1 Answers1

2

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).

mcmahoniel
  • 133
  • 7
  • I will check out Robot when I get home, but do I manually have to move the mouse to the position I want it to? So I'll have to calculate where it's "supposed" to be? – Chexxor Mar 28 '16 at 02:16
  • 1
    Yes. With `mouseMove`, you can explicitly set the coordinates of the cursor. One example would be to watch the X and Y coordinates of the cursor constantly and simply reset the X or Y to prevent the mouse ever leaving the border of the window. Alternatively, you could pop the cursor back to the center of the window instead. The specific implementation would be up to you. – mcmahoniel Mar 28 '16 at 03:13