Search code examples
javaawtprocessingmousemoveawtrobot

need a java-processing class for moving mouse to window center


I have been using Processing with java.awt.Robot and java.awt.Dimension to lock the mouse into the center of the screen. robot moves the mouse to relative to to the monitor, I need it to be relative to the window. I need a suggestion for how to get window location or a class like robot that works relative to the window.

void MouseLock() {
  
  if(mouseX != screensizex/2 || mouseY != screensizey/2) {
    xmovement =  (mouseX - screensizex/2);
    Ymovement =  (mouseY - screensizey/2);
          try {
            Robot screenWin = new Robot();
            screenWin.mouseMove((int)screensizex/2, (int)screensizey/2);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
}

anything that gets my xmovement and ymovement while disabling the mouse from leaving the program will work


Solution

  • You can get the window's top-left location with this renderer-independent method and use that to location the coordinate of the center of the sketch. Note you might have to account for the height of the titlebar.

    PVector getWindowLocation() {
    
      PVector windowLocation = new PVector();
    
      switch (sketchRenderer()) {
      case P2D:
      case P3D:
        com.jogamp.nativewindow.util.Point p = new com.jogamp.nativewindow.util.Point();
        ((com.jogamp.newt.opengl.GLWindow) surface.getNative()).getLocationOnScreen(p);
        windowLocation.x = p.getX();
        windowLocation.y = p.getY();
        break;
      case FX2D:
        final processing.javafx.PSurfaceFX FXSurface = (processing.javafx.PSurfaceFX) surface;
        final javafx.scene.canvas.Canvas canvas = (javafx.scene.canvas.Canvas) FXSurface.getNative();
        final javafx.stage.Stage stage = (javafx.stage.Stage) canvas.getScene().getWindow();
        windowLocation.x = (float) stage.getX();
        windowLocation.y = (float) stage.getY();
        break;
      case JAVA2D:
        java.awt.Frame f = (java.awt.Frame) ((processing.awt.PSurfaceAWT.SmoothCanvas) surface.getNative())
            .getFrame();
        windowLocation.x = f.getX();
        windowLocation.y = f.getY();
        break;
      }
    
      return windowLocation;
    }