To automate certain tasks, sometimes we might need to simulate the real mouse click. In this article we will see how to simulate the real mouse click in Java.

Using Robot class

Using the Robot class, we can generate native system input events programmatically and can simulate various user input actions including mouse clicks.

Import required classes

import java.awt.*;
import java.awt.event.InputEvent;

See the following example on how to simulate the mouse click.

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

            // Move the mouse cursor to a specific position
            int x = 500; // X-coordinate
            int y = 300; // Y-coordinate
            robot.mouseMove(x, y);

            // Simulate a left mouse button click
        } catch (AWTException e) {

robot.mouseMove(x, y) This moves the mouse cursor to the specified coordinates (x, y) on the screen.

robot.mousePress(InputEvent.BUTTON1_DOWN_MASK) simulates pressing the left mouse button.

robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK) simulates releasing the left mouse button.


Categorized in:

Tagged in: