在 Java 中移动光标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4231458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moving the cursor in Java
提问by Supuhstar
I want to make an app that measures the cursor's distance from the center of a component and then moves the cursor back to the center (like most PC video games do). Does anyone have any suggestions?
我想制作一个应用程序来测量光标与组件中心的距离,然后将光标移回中心(就像大多数 PC 视频游戏一样)。有没有人有什么建议?
采纳答案by Faisal Feroz
Robot class can do the trick for you. Here is a sample code for moving the mouse cursor:
机器人课程可以为您解决问题。这是移动鼠标光标的示例代码:
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) {
}
回答by Blake T
Hi this will just be adding on. I use a Raspberry PI a lot so I've had to learn how to optimize my code this will be a lot shorter.
嗨,这将只是添加。我经常使用 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();
}
don't forget to import:
不要忘记导入:
import java.awt.*;