Search code examples
javamultithreadinginfinite-looprunnable

Button stuck, need to break infinite loop in java


I am writing a program that will move the mouse a certain distance in a given time period. So I need the algorithm to go as:

Click start

while(true){
    move mouse to point x
    sleep for n seconds
}

Which works, but when ran as a thread the start button is still pressed because the thread is continuously running. Therefore, I am locked out from even exiting that program(as with any infinite loop) and I am unable to set the boolean to "false" to stop the while loop. What do I need to do so that this thread can run in the background and still give me access to click the stop button and have the mouse stop moving?

In my main class I have:

public void actionPerformed(ActionEvent e) {

            if (e.getSource() == btnStart) {
                Thread t = new Thread(new Mover(1000, true));
                t.run();
            }
        }

Thread Class:

import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;

public class Mover implements Runnable {

    int time;
    boolean startStop;

    public Mover(int x, boolean b) {

        time = x;
        startStop = b;

    }

    @Override
    public void run() {

        while (startStop) {
            // TODO Auto-generated method stub

            //Get x position
            int intX = MouseInfo.getPointerInfo().getLocation().x;
            // String intx = Integer.toString(intX);

            //Get y position
            int intY = MouseInfo.getPointerInfo().getLocation().y;

            Robot robot;
            try {
                robot = new Robot();
                robot.mouseMove(intX - 100, intY);
            } catch (AWTException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }// Close while loop
    }

}

Solution

  • Create a setter for the boolean in the Mover class:

    public void setStartStop(boolean value) {
        startStop = value;
    }
    

    Then keep a reference to the Mover in your main class.

    Mover mover = new Mover(1000, true);
    Thread thread = new Thread(mover);
    thread.start();
    //do stuff
    mover.setStartStop(false);
    

    This allows your external (i.e., main) thread to affect the other thread while it's running. Once you kick off the thread, your main thread should continue execution as normal.