This post shows how to to do mouse press in Java using the program instead of manual click

January 14, 2019

In this post, we will discuss how to handle mouse press programmatically without having manual intervention. This is sometimes handy when we are in need to perform mouse click using the program.

Below mentioned is the code snippet showing the mouse press using Java's in-built awt class Robot.

// Create instance of Robot Class
Robot bot = new Robot();

// Move the bot position to given coordinates
bot.mouseMove( x, y );

// Press and Release the mouse to simulate click
bot.mousePress( InputEvent.BUTTON1_MASK );
bot.mouseRelease( InputEvent.BUTTON1_MASK );

System.out.println( "Mouse clicked at: " + x + " : " + y );

This is how we can simply perform mouse click using a program. The below-mentioned code shows a further enhancement to it by using a simple implementation of Thread to listen for the change and perform the click.

package com.myapp.utilities;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;

public class MouseClickUtility implements Runnable {

public static boolean active = false;
public static int interval = 500;

@Override
public void run() {

try {

while( true ) {

if( active ) {

int mouseY = MouseInfo.getPointerInfo().getLocation().y;
int mouseX = MouseInfo.getPointerInfo().getLocation().x;

System.out.println( "Mouse positioned at: " + mouseY + " : " + mouseX );

Robot bot = new Robot();

bot.mouseMove( mouseY, mouseX );

bot.mousePress( InputEvent.BUTTON1_MASK );
bot.mouseRelease( InputEvent.BUTTON1_MASK );

System.out.println( "Mouse clicked at: " + x + " : " + y );
}

Thread.sleep( interval );
}
}
catch( InterruptedException e ) {

e.printStackTrace();
}
catch( AWTException e ) {

e.printStackTrace();
}
}
}

Write a Comment

Click on the captcha image to get new code.
Discussion Forum by DISQUS