Trying to make an autoclicking loop

Hey guys, i’m trying to make a autoclicker for my buddy and when the autoclicking loop starts the java program becomes unresponsive. no matter what i do it seems the program will always crash

    public Click click = new Click();
    public void handleAutoClickerStart(ActionEvent event) {
        //Ison determines weather or not the loop is running
        boolean isOn;
        int msDelay = Integer.parseInt(delay.getText());
        click.setDelay(msDelay);
        isOn = true;

        while (isOn == true) {
            if (close.isPressed()) {
                isOn = false;
                break;
            }
            try {

                click.clickMouse(InputEvent.BUTTON1_DOWN_MASK);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

This is a java FX program for UI

How can i rewrite the looping so that I can have the program run for a while and i can stop the loop whenever the user clicks close?

Thanks :slight_smile:

I haven’t had any experience with JavaFX or with the Click class in Java, but I think setDelay(int) uses some sort of internal delay that blocks the click event from firing too fast.
If that’s the case I think that your while (isOn == true) loop may be running an infinite loop and locking up your UI thread. I would suggest maybe running a timer class with your msDelay and firing the click.clickMouse(...) call. Something like java.util.Timer may work?

import java.util.Timer;
import java.util.TimerTask;

public void handleAutoClickerStart(ActionEvent event) {

    /* set up code */
    boolean isOn = true;

    Timer timer = new Timer("autoclicker");

    // create task that will be execute with each timer loop
    TimerTask task = new TimerTask(() -> {
        click.clickMouse(InputEvent.BUTTON1_DOWN_MASK);
        if (!isOn) {
            // stops the timer from continuing
            timer.cancel();
        }
    });

    // tell the timer to execute `task` after an initial delay of `msDelay` and 
    // every `msDelay` after until asked to stop
    timer.scheduleAtFixedRate(task, msDelay, msDelay);

}

I figured out what the problem was on my own,

The issue was with taking control over the main thread to preform the clicking function. Making the main thread loop infinitely caused the program to become unresponsive to windows. Separating the main thread and using a sub thread to preform the clicking was the solution

In hindsight seems odd, yet also obvious at the same time.

thank you @dannyshadd0w for the help