Move mouse cursor in Java on Windows OS

Hi everyone. In this article we will learn about, moving the mouse cursor on windows OS using the Java programming language.

Moving Mouse Cursor Using Java On Windows OS

Table of contents

  • Prerequisites
  • Program
  • Explanation of the program
  • Conclusion

Prerequisites

  • Java JDK installed on your machine
  • Basic understanding of Java programming language.

Program

This is the program for the Moving  a mouse cursor in Java on Windows OS.

import java.awt.AWTException;
import java.awt.Robot;

public class MoveMouseCursor {
    public static void main(String[] args) {
        try {
            // Create a Robot instance
            Robot robot = new Robot();

            // Set the desired screen coordinates (x, y) for the cursor
            int x = 500; // X-coordinate
            int y = 300; // Y-coordinate

            // Move the mouse cursor to the specified location
            robot.mouseMove(x, y);

            System.out.println("Mouse moved to: (" + x + ", " + y + ")");
        } catch (AWTException e) {
            System.err.println("Robot class not supported: " + e.getMessage());
        }
    }
}

 

Output

Mouse moved to: (500, 300)

How its work

  • Robot Class:Provides methods for controlling the mouse and keyboard.
  • mouseMove(x, y) Method: Moves the cursor to the specified screen coordinates.
  • Screen Coordinates: x and y are measured from the top-left corner of the primary screen (0, 0).

Steps to run the program

1.Compile the java file

javac MoveMouseCursor.java

2.Run the java program

java MoveMouseCursor

Explanation of the Program

Here is the simple explanation of the program 

1. The program moves the mouse cursor to a specific position on the screen using Java.

2. Steps in the program 

  •   Import `java.awt.Robot`: This class helps control the mouse and keyboard.
  •  Create a `Robot` object: It allows you to simulate mouse movements.
  •  Use `robot.mouseMove(x, y)`: Moves the mouse to the given `(x, y)` coordinates on the screen.

3. Coordinates

  •  `(0, 0)` is the top-left corner of the screen.
  •  You can change `x` and `y` to move the cursor to a different location.

4. Example:

      If `x = 500` and `y = 300`, the cursor moves 500 pixels to the right and 300 pixels down from the top-left corner. 

Conclusion

              The program demonstrates how to control the mouse cursor programmatically in Java using the Robot class. When executed, it successfully moves the cursor to a specific position (500, 300) on the screen. If the system supports the Robot class and the coordinates are within the screen’s resolution, the program runs smoothly.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top