简体   繁体   English

无法使用 JavaFX 更改可运行的接口

[英]Can't make changes to interface in a runnable with JavaFX

In my program, I am running a separate script and I am using concurrency to run the separate script, and therefore using a class implementing Runnable.在我的程序中,我正在运行一个单独的脚本,并且我正在使用并发来运行单独的脚本,因此使用了实现 Runnable 的 class。

When the the separate thread is running, I want there to be a different graphic to when the thread is not running so the user can see if something is happening after pressing the button.当单独的线程运行时,我希望有一个与线程未运行时不同的图形,以便用户可以在按下按钮后查看是否发生了某些事情。

The function of the thread is working fine, it is just that after the thread has finished, the button graphic does not change when I try to change the graphic from inside the thread.线程的 function 工作正常,只是线程完成后,当我尝试从线程内部更改图形时,按钮图形没有改变。

Code related to the issue:与问题相关的代码:

In the class:在 class 中:

        downloadSongs.setOnMousePressed(new EventHandler<MouseEvent>() {  
        @Override
        public void handle(MouseEvent event) { 
            
            try{
                if(dnld.isAlive()==true){
                    
                }else{
                    dnld = new Thread(new DownloadThread());
                    dnld.start();
                }
            }catch(Exception e){
                dnld = new Thread(new DownloadThread());
                dnld.start();
            }

In the thread:在线程中:

public class DownloadThread implements Runnable{
    public void run(){
        *function of run which works*
        try {
             *more code*
            } catch (Exception e) {
                            ErrorPopUp.Display();
                            //add in the red line around it being added/taken away
                            Download.downloadSongs.setGraphic(Download.download);
        }
        Download.downloadSongs.setGraphic(Download.download);

You cannot change the user interface outside the application thread.您不能在应用程序线程之外更改用户界面。 All user interface code checks isFxApplicationThread() and throw an exception if not.所有用户界面代码都会检查isFxApplicationThread() ,如果没有则抛出异常。

You either need to call runLater to ensure your update is executed on the application thread, or implement a Task您要么需要调用runLater以确保您的更新在应用程序线程上执行,要么实现一个Task

To learn more about concurrency in JavaFX you can check out the Concurrency in JavaFX trail .要了解有关 JavaFX 中的并发性的更多信息,您可以查看 JavaFX 中的并发性线索

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM