Click Programmatically

Q: How to click programmatically?

Suppose there is a need(like system goes to sleep if it is idle after a particular interval of time) and you want to keep the system alive. One of the ways out is automatic clicking of a mouse.

Go through the following program Enjoy

— —

import java.awt.AWTException;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;

public class DoNotSleep {

public static void main(String args[]) {

    int delay = 1000;                         // delay for 1sec.
    int period = 1000;                        // repeat every 1 sec.
    Timer timer = new Timer();                //creates a object of Timer class
    final Frame f = new Frame();              //creates a object of Frame class

    /* Creates a frame */
        Label l=new Label("Do Not Sleep!");

        /* Listener is added to the frame. when a user clicks on the close button the window gets closed and the program will get shut down */
        f.addWindowListener (
            new WindowAdapter() {
                @Override public void windowClosing(WindowEvent e) {

        /* Here we schedule the click event using pre specified delay and period variables*/
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
            try {
                Robot robot = new Robot();                          // Creates a Robot class object
                robot.mousePress(InputEvent.BUTTON1_MASK);          // Mouse press event
                robot.mouseRelease(InputEvent.BUTTON1_MASK);        // Mouse release event
        catch (AWTException e) {
    }, delay, period);


Click Programmatically