无法使用 JavaFX 更改可运行的界面

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

在我的程序中,我 运行 正在使用一个单独的脚本,并且我正在对 运行 单独的脚本使用并发,因此使用 class 实现 Runnable。

当单独的线程是 运行ning 时,我希望在线程不是 运行ning 时有一个不同的图形,这样用户可以在按下按钮。

线程的功能运行良好,只是在线程完成后,当我尝试从线程内部更改图形时,按钮图形没有改变。

问题相关代码:

在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();
            }

在话题中:

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);

您不能在应用程序线程外更改用户界面。所有用户界面代码都会检查 isFxApplicationThread(),如果没有则抛出异常。

您要么需要致电 runLater to ensure your update is executed on the application thread, or implement a Task

要了解有关 JavaFX 中并发性的更多信息,您可以查看 Concurrency in JavaFX trail