在Java中移动光标

Sup*_*tar 20 java cursor

我想创建一个应用程序,测量光标距组件中心的距离,然后将光标移回中心(就像大多数PC视频游戏一样).有没有人有什么建议?

Fai*_*roz 36

机器人类可以为你做到这一点.以下是移动鼠标光标的示例代码:

try {
    // These coordinates are screen coordinates
    int xCoord = 500;
    int yCoord = 500;

    // Move the cursor
    Robot robot = new Robot();
    robot.mouseMove(xCoord, yCoord);
} catch (AWTException e) {
}
Run Code Online (Sandbox Code Playgroud)


小智 6

嗨,这只是添加。我经常使用 Raspberry PI,所以我必须学习如何优化我的代码,这会短很多。

try {
    //moves mouse to the middle of the screen
    new Robot().mouseMove((int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2, (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2);
    //remember to use try-catch block (always, and remember to delete this)
} catch (AWTException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

不要忘记导入:

import java.awt.*;
Run Code Online (Sandbox Code Playgroud)

  • 但无论如何,它都会用你的代码创建临时变量。点链是语法糖,但最终每个方法的返回值都必须在某个地方保存和跟踪 (5认同)
  • 此外,您的计算量更大,必须两次获取默认工具包及其屏幕尺寸。由于默认工具包是单例,因此预先保存对它的引用不会占用更多内存,但会节省计算时间。我不确定屏幕尺寸,但我愿意打赌它也会被缓存和返回,因此保存对此的引用也不应该占用更多内存。 (2认同)