如果我有方法的类:JavaFX并发性:我可以在任务中运行对象方法吗?
class Car{
private String engineRPM;
public Car(){}
public String idleEngine(){
if (engineOn()){
engineRPM = getEngineRPM();
}
return engineRPM;
}
}
如何在主后台线程运行在任务中的方法,然后利用其返回值,并更新GUI?
public class Main extends Application {
Car myCar;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/entry.fxml"));
Parent root = loader.load();
this.mainController = (SystemMessage) loader.getController();
primaryStage.setTitle("Car");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
//perform background task of class method here
myCar = new Car();
myCar.startEngine();
String RPM = myCar.engineIdle(); //
this.mainController.postMessage(RPM);
}
您可以使用Platform.runLater(Runnable ...)来执行此操作。请检查此:https://stackoverflow.com/questions/13784333/platform-runlater-and-task-in-javafx – Serge
@Serge'Platform.runLater(...)'在FX应用程序线程上运行的东西,而不是后台线程。所以我想你的意思是最后的UI更新应该使用'Platform.runLater(...)'。这从评论中不明确。 –
@James_D是的,这就是我的意思。对不起,截断的音符。 – Serge