需要一个java处理类来将鼠标移动到窗口中心

kuhbmx9i  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(618)

我一直在使用java.awt.robot和java.awt.dimension处理将鼠标锁定在屏幕中央。机器人移动鼠标相对于显示器,我需要它相对于窗口。我需要一个关于如何获得窗口位置或像机器人这样的类,相对于窗口的工作建议。

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();
          }
        }
}

任何在禁止鼠标离开程序的同时得到我的xmovement和ymovement的东西都可以工作

41ik7eoe

41ik7eoe1#

可以使用此独立于渲染器的方法获取窗口的左上角位置,并使用该位置来定位草图中心的坐标。请注意,您可能需要考虑标题栏的高度。

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;
}

相关问题