4 Replies Latest reply: Mar 20, 2010 10:04 AM by 843853 RSS

    Locking/Capturing Mouse to Window

      Hello all,

      Currently I'm busy making a RTS game (full screen). Navigating over the map can be done by moving the mouse to the sides of the window. But when using a second monitor, my mouse is moving to the second screen. So i was wondering if i could snap/lock/capture the mouse to the main window (a behavior commonly seen in games).

      Thanks in advance,
        • 1. Re: Locking/Capturing Mouse to Window
          Yes, using MouseInfo, Robot, and a Timer you can do just that. Use a Timer--javax.swing.Timer to get a loop going and check MouseInfo when it activates, if your mouse is out of the Panel, then move it back.

          You may also be able to accomplish this with just a MouseMotionListener, but I'd be afraid of getting out of the screen and not being notified.
          • 2. Re: Locking/Capturing Mouse to Window
            Thanks for your fast reply, i will look into it asap! :)
            • 3. Re: Locking/Capturing Mouse to Window
              I looked into Robot and MouseInfo, got it to work.The code is being executed by a custom Thread, and sometimes i get a 'java.lang.InterruptedException: sleep interrupted' error, wich is being thrown from the robot.
              java.lang.InterruptedException: sleep interrupted
                   at java.lang.Thread.sleep(Native Method)
                   at java.awt.Robot.delay(Unknown Source)
                   at java.awt.Robot.autoDelay(Unknown Source)
                   at java.awt.Robot.afterEvent(Unknown Source)
                   at java.awt.Robot.mouseMove(Unknown Source)
              Any ideas why this is happening and how it can be solved?

              Thanks again,
              • 4. Re: Locking/Capturing Mouse to Window
                Thread.sleep() throws an InterruptedException. You need to handle it appropriately in a try/catch block.