You could try to save the Thread
object to a global variable and stop it when the toggleButton
is pressed again.
Using the wait
method on the thread will not work, because wait
does not work like you expect it (see Object.wait() in javadoc)
The second problem (IllegalStateException: Not on FX application thread) is probably caused by the method performAction(ActionEvent)
because it tries to change things in the GUI, which is not allowed from another thread than the application thread. To avoid this you can use Platform.runLater(Runnable)
(see javadock or this post)
A solution could look like this:
private Thread thread;
//call this method every time the toggle button is pressed
private void play(final ActionEvent ae) {
if (thread == null) {
//start in a new thread
thread = new Thread(new Runnable() {//better add a runnable to the new Thread than overwriting the run method of Thread
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {//run until the thread is interrupted
try {
Thread.sleep(speed);
//run this in platform to avoid the IllegalStateException that no fx thread is used
Plaform.runLater(() -> performAction(ae));
}
catch (InterruptedException e) {
//e.printStackTrace();
//set the interrupted flag again (was unset when exception was caught)
Thread.currentThread().interrupt();
}
}
}
});
thread.start();
}
else {
//stop the current thread
thread.interrupt();
thread = null;
}
}