How do I keep the mouse constrained inside my sketch window please?

edited December 2015 in Questions about Code

I want my mouse to move inside the sketch window. I know I have to use the robot class. But when I give my robot values it moves all over the screen. How do I keep the mouse constrained inside my sketch window please?

Answers

  • edited December 2015 Answer ✓

    This is a very hacked together example, but this will contain the cursor inside the sketch window. It is possible to "break free" from the sketch if you move your mouse fast enough, though.

    import java.awt.Robot;
    import java.awt.AWTException;
    import java.awt.Point;
    import java.awt.MouseInfo;
    
    int windowX, windowY, absMouseX, absMouseY;
    
    void setup() {
      size(400, 400);
    }
    
    void draw() {
      MouseInfo.getPointerInfo();
      Point pt = MouseInfo.getPointerInfo().getLocation();
      absMouseX = (int)pt.getX();
      absMouseY = (int)pt.getY();
      if(mouseX > 50 && mouseX < width-50 && mouseY > 50 && mouseY < height-50
                      && abs(mouseX-pmouseX) == 0 && abs(mouseY-pmouseY) == 0) {
        windowX = (int)(absMouseX-mouseX);
        windowY = (int)(absMouseY-mouseY);
      }
      int x = -1, y = -1;
      if(absMouseX < windowX)
        x = windowX;
      else if(absMouseX > windowX+width)
        x = windowX + width;
      if(absMouseY < windowY)
        y = windowY;
      else if(absMouseY > windowY+height)
        y = windowY + height;
      if(!(x == -1 && y == -1))
        try {
          Robot bot = new Robot();
          bot.mouseMove(x == -1 ? absMouseX : x, y == -1 ? absMouseY : y);
        }
        catch (AWTException e) {}
    }
    
  • Thank you DCRaven

Sign In or Register to comment.