27

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?

2 Answers 2

48

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) {
}
0
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.*;
4
  • 1
    I'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 -
    Commented Sep 18, 2015 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
    Commented Sep 18, 2015 at 15:46
  • 5
    but 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 -
    Commented Sep 18, 2015 at 16:40
  • 2
    Also, 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 -
    Commented Sep 18, 2015 at 18:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.