【javaFX基础】 “Not on FX application thread; currentThread = Thread-3“问题解决方法
一、问题描述
运行以下代码时:
button.setOnAction(event->{//新建线程,避免画面卡顿Thread thread =new Thread(()->{String newValue ="测试语句";label.setText(newValue);//更新UI});thread.start();});
出现以下提示:非法操作,要更新控件需要在FX application 线程里,其他线程不允许!
Exception in thread "Thread-3" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-3

二、解决方法
利用javaFX中 Platform的静态方法runLater,将更新UI的代码放在里面。原理:runLater将任务放在队列里,当线程空闲时将执行队列里的任务,相当于在application 线程里执行。
button.setOnAction(event->{Thread thread =new Thread(()->{String newValue ="测试代码";Platform.runLater(()->{label.setText(newValue);//更新UI});});thread.start();});
完整代码,运行程序,点击按钮,标签文字对应变化:
package org.example.testsc1;import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;import java.io.IOException;public class HelloApplication extends Application {@Overridepublic void start( Stage primaryStage) throws IOException {/*FXMLLoader fxmlLoader =new FXMLLoader();fxmlLoader.setLocation(getClass().getResource( "Sc.fxml"));Parent root=fxmlLoader.load();Scene scene =new Scene(root);HelloController controller =fxmlLoader.getController();controller.circleLocationBind(scene);//实现圆随页面大小变化而位置变化
*/Label label = new Label( "你在干什么?");label.setLayoutX(200);label.setLayoutY(50);Button button = new Button("获取");button.setLayoutX(200);button.setLayoutY(100);button.setOnAction(event->{Thread thread =new Thread(() ->{String newValue ="测试代码";Platform.runLater(()->{label.setText(newValue);//更新UI});});thread.start();});
/*primaryStage.setTitle("Hello World");primaryStage.setScene(scene);primaryStage.show();*/AnchorPane pane =new AnchorPane();pane.getChildren().addAll(label, button);Scene scene =new Scene(pane,500, 500);primaryStage.setScene(scene);primaryStage.setScene(scene);primaryStage.setResizable(false);primaryStage.setTitle("Hello");primaryStage.show();}public static void main(String[] args){ launch(args);}
}

