java - 按两次 ToggleButton 时无法在自定义线程中执行 while 循环(仅适用于第一次)

标签 java javafx fxml

我的程序的工作方式是,按下按钮时会调用一个方法。然后,我的想法是,我有一个新线程,它有一个 while 循环,每隔指定的时间调用另一个方法,直到再次按下切换按钮。我该如何编程这样的事情呢?我尝试了 Thread.wait() 但它会导致 GUI 更新出现问题。

已解决。谢谢!

最佳答案

您可以尝试将Thread对象保存到全局变量中,并在再次按下toggleButton时停止它。

在线程上使用 wait 方法将不起作用,因为 wait 不会像您期望的那样工作(请参阅 Object.wait() in javadoc )

第二个问题(IllegalStateException:不在 FX 应用程序线程上)可能是由方法 performAction(ActionEvent) 引起的,因为它尝试更改 GUI 中的内容,而其他线程不允许这样做应用程序线程。为了避免这种情况,您可以使用 Platform.runLater(Runnable) (请参阅 javadockthis 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/

相关文章:

java - Docker:组合多个图像

pdf - 开源 PDFViewer Javafx

java - 我应该如何让我的玩家矩形跳跃?

controller - 具有多个不同 Controller 的 JavaFX 1 FXML 文件?

listener - 以编程方式删除使用 FXML 添加的监听器?

java - ProGuard 破坏 JavaFX 应用程序

java - 将图像上传到 Firebase 存储后,无法将图像 url 放入 Firestore 数据库

Java AWT : Remove frame title bar and add customised title Bar

java - 与 picasso 的共享元素转换即使在实现回调后也无法正常工作

java - (JavaFX 8) css 按钮边框和背景色问题