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?
Asked
Active
Viewed 5.9k times
2 Answers
46
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) {
}

Faisal Feroz
- 12,458
- 4
- 40
- 51
6
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.
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.*;

Rory McCrossan
- 331,213
- 40
- 305
- 339

Blake T
- 61
- 1
- 2
-
1I'm confused... are you talking about storing your source code on the Pi? Or does this magically make the compiled file smaller? If the latter, why the instruction to delete the comment? – Ky - Sep 18 '15 at 15:41
-
Well the less variables the better, you want to make it very compact so it doesn't create an overflow on the RAM. – Blake T Sep 18 '15 at 15:46
-
5but it makes temporary variables with your code, anyway. Dot-chains are syntactic sugar, but in the end, each method's return value must be saved and tracked somewhere – Ky - Sep 18 '15 at 16:40
-
2Also, yours is computationally heavier, having to fetch the default toolkit and its screen size twice. Since the default toolkit is a singleton, saving a reference to it beforehand won't take up any more memory, but will save computation time. I'm not sure about the screen size, but I'd be willing to bet that's also cached and returned, so saving a reference to that shouldn't take more memory, either. – Ky - Sep 18 '15 at 18:17