Robot Tutorial - Make a Simple Auto-Clicker

This is a tutorial on how to use the Robot class in java. In this tutorial we will be making a simple auto-clicker.

The code of the auto-clicker:


import java.awt.*;
import java.awt.event.*;
import java.io.*;

/**
 * Simple auto-clicker.
 * 
 * @author Bradley Carels
 */
public class AutoClicker {

	public static int rate = 0;

	public static void main(String[] args) {
		while (rate == 0) {
			try {
				System.out.println("Speed of the auto-clicker (in miliseconds):");
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				try {
					rate = Integer.parseInt(in.readLine());
					if (rate < 500) {
						rate = 0;
						System.out.println("Must be at least 500 miliseconds.");
					}
				} catch (NumberFormatException ex) {
					System.out.println("Error - please try again.");
				}
			} catch (IOException e) {}
		}
		try {
			Robot robot = new Robot();
			while (true) {
				try {
					Thread.sleep(rate);
					robot.mousePress(InputEvent.BUTTON1_MASK);
					robot.mouseRelease(InputEvent.BUTTON1_MASK);
				} catch (InterruptedException ex) {}
			}
		} catch (AWTException e) {}
	}

}

Explaned
First, the first portion of the code:


		while (rate == 0) {
			try {
				System.out.println("Speed of the auto-clicker (in miliseconds):");
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				try {
					rate = Integer.parseInt(in.readLine());
					if (rate < 500) {
						rate = 0;
						System.out.println("Must be at least 500 miliseconds.");
					}
				} catch (NumberFormatException ex) {
					System.out.println("Error - please try again.");
				}
			} catch (IOException e) {}
		}

The while statement will keep checking for input until a valid number is entered. The entered value is the rate (in miliseconds) that the auto-clicker will run.

Now, the main code of the auto-clicker:


		try {
			Robot robot = new Robot();
			while (true) {
				try {
					Thread.sleep(rate);
					robot.mousePress(InputEvent.BUTTON1_MASK);
					robot.mouseRelease(InputEvent.BUTTON1_MASK);
				} catch (InterruptedException ex) {}
			}
		} catch (AWTException e) {}

First, a new robot constructor is created. We then set up a thread that runs at the rate set in the previously shown code. Every tick, the mouse is pressed and then released through our robot constructor.

Hopefully this tutorial has helped you understand how the Robot class works. If you have any questions, feel free to ask.

does this work for non-java programs?

java.awt.robot does everything on the highest level - it just moves from pixel to pixel. This is an extremely simple example of no mouse movement.
@OP why use thread.sleep() when you can use robot.delay()?

Beyond gaming this also works wonderfully as a “keep alive” for some RDP programs. ;D