我正在將 javaFX 與 FXML 文件一起使用。單擊按鈕,系統(tǒng)將一個函數調用到 FxmlController.java 中,該函數需要一些時間來詳細說明結果。在細化過程中,GUI 似乎凍結,直到獲得結果。我知道對于 GUI 我應該使用線程,但我不知道如何。但是,這是調用 onClick 按鈕的 FXMLController.java 的一段代碼: private void printOut() { List<String> listString = null; Hyperlink hyperLink = new Hyperlink("test"); VBox vBox = Main.getVbox(); vBox.getChildren().clear(); listString = readAllDoc(); //this is the function that needs time to run vBox.getChildren().add(hyperLink); } 此外,函數 printOut 在 fxml 文件中被調用......見下文:<Button fx:id="read" layoutX="34.0" layoutY="401.0" mnemonicParsing="false" text="Read All" onAction="#printOut" />主要是這樣的:public void start(Stage stage) throws IOException{ // Create the FXMLLoader FXMLLoader loader = new FXMLLoader(); // Path to the FXML File String fxmlDocPath = getClass().getResource("MyFXML.fxml").getPath(); FileInputStream fxmlStream = new FileInputStream(fxmlDocPath); // Create the Pane and all Details AnchorPane root = (AnchorPane) loader.load(fxmlStream); setPrimaryRoot(root); ScrollPane sp = (ScrollPane) root.getChildren().get(2); VBox vb = (VBox) sp.getContent(); setScrollPane(sp); setVbox(vb); // Create the Scene Scene scene = new Scene(root); // Set the Scene to the Stage stage.setScene(scene); // Set the Title to the Stage stage.setTitle("Project"); setPrimaryStage(stage); // Display the Stage stage.show();}如何在不凍結 GUI 的情況下在后臺運行函數“readAllDoc”?謝謝
1 回答

慕容708150
TA貢獻1831條經驗 獲得超4個贊
解決了!
我寫了一個新類extenderTask:
public class extenderTask extends Task {
private List<String> listString;
@Override
protected List<String> call() throws Exception {
this.list = functThatTakeLotOfTime();
return this.listString;
}
}
并在控制器中:
extenderTask task = new extenderTask();
new Thread(task).start();
task.setOnSucceeded(e -> {
setListYourVariable((List<String>) task.getValue()); ...
...(all other action)...
}
很容易??!:-)
添加回答
舉報
0/150
提交
取消