我的程序的工作方式是,按下按钮时会调用一个方法。然后,我的想法是,我有一个新线程,它有一个 while 循环,每隔指定的时间调用另一个方法,直到再次按下切换按钮。我该如何编程这样的事情呢?我尝试了 Thread.wait() 但它会导致 GUI 更新出现问题。
已解决。谢谢!
最佳答案
您可以尝试将Thread
对象保存到全局变量中,并在再次按下toggleButton
时停止它。
在线程上使用 wait
方法将不起作用,因为 wait
不会像您期望的那样工作(请参阅 Object.wait() in javadoc )
第二个问题(IllegalStateException:不在 FX 应用程序线程上)可能是由方法 performAction(ActionEvent)
引起的,因为它尝试更改 GUI 中的内容,而其他线程不允许这样做应用程序线程。为了避免这种情况,您可以使用 Platform.runLater(Runnable)
(请参阅 javadock 或 this post )
解决方案可能如下所示:
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;
}
}
关于java - 按两次 ToggleButton 时无法在自定义线程中执行 while 循环(仅适用于第一次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58927419/