Timer period doesn't work with Robot class

Viewed 32

I have the following code:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;

import javax.swing.*;

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Title");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton start = new JButton();
        start.setText("Start");
        JButton stop = new JButton();
        stop.setText("Stop");
        frame.getContentPane().add(stop, BorderLayout.PAGE_END);
        frame.getContentPane().add(start, BorderLayout.PAGE_START);
        frame.setSize(200, 100);
        frame.pack();
        frame.setVisible(true);
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Timer timer = new Timer();
                timer.schedule(new Clicker(), 0, 5000);
            }
        });
        stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            
            }
        });
    }
}

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.TimerTask;

public class Clicker extends TimerTask {
    public void run() {
        click();
    }
    public void click() {
        System.out.println("Clicked");
        try {
            Robot robot = new Robot();
            // Simulate a key press
            robot.keyPress(KeyEvent.VK_SPACE);
            robot.keyRelease(KeyEvent.VK_SPACE);

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

For some reason, If I have the System.out.println("Clicked"); only in the click function all is working perfect and the delay is occurring for 5000ms.

As soon as I add the:

try {
    Robot robot = new Robot();
    // Simulate a key press
    robot.keyPress(KeyEvent.VK_SPACE);
    robot.keyRelease(KeyEvent.VK_SPACE);
} catch (AWTException e) {
    e.printStackTrace();
}

The function is executed in a loop and ignores the delay. What am I doing wrong?

Thanks.

0 Answers
Related