我正在使用 javaFX 和 FXML 文件。
点击按钮,系统调用一个函数到 FxmlController.java 中,需要一些时间来详细说明结果。
在细化过程中,GUI 似乎卡住,直到获得结果。 我知道对于 GUI 我应该使用 threding 但我不知道如何。 然而,这是在单击按钮时调用的我的 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”?谢谢
最佳答案
解决了!
我写了一个新类 extenderTask:
public class extenderTask extends Task {
private List<String> listString;
@Override
protected List<String> call() throws Exception {
this.list = functThatTakeLotOfTime();
return this.listString;
}
}
在 Controller 中:
extenderTask task = new extenderTask();
new Thread(task).start();
task.setOnSucceeded(e -> {
setListYourVariable((List<String>) task.getValue()); ...
...(all other action)...
}
很简单!! :-)
关于JavaFX 窗口在内部阐述期间没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52678066/