猿问

JavaFX 窗口在内部细化期间没有响应

我正在将 javaFX 与 FXML 文件一起使用。


单击按钮,系统将一个函数调用到 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”?谢谢


哆啦的时光机
浏览 146回答 1
1回答

慕容708150

解决了!我写了一个新类extenderTask:public class extenderTask extends Task {private List<String> listString;@Overrideprotected List<String> call() throws Exception {&nbsp; &nbsp; this.list = functThatTakeLotOfTime();&nbsp; &nbsp; return this.listString;&nbsp; }}并在控制器中:extenderTask task = new extenderTask();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new Thread(task).start();task.setOnSucceeded(e -> {setListYourVariable((List<String>) task.getValue()); ......(all other action)...}很容易!!:-)
随时随地看视频慕课网APP

相关分类

Java
我要回答