gpt4 book ai didi

JavaFX Action 事件语句执行顺序

转载 作者:行者123 更新时间:2023-12-02 12:22:13 26 4
gpt4 key购买 nike

public class MainController {
@FXML
public Button browse_report;
@FXML
public Button browse_directory;
@FXML
public Button export;
@FXML
public Button close;
@FXML
public Label report;
@FXML
public Label directory;
@FXML
public Label processing;
@FXML
public TextField report_text;
@FXML
public TextField directory_text;
@FXML
public ProgressBar pg = new ProgressBar();



public void closeButton(ActionEvent e) {
System.exit(0);
}

public void getReport(ActionEvent e) {
FileChooser fc = new FileChooser();
File file=fc.showOpenDialog(null);
report_text.setText(file.getAbsolutePath());
}

public void getDirectory(ActionEvent e) {
DirectoryChooser dc = new DirectoryChooser();
File file =dc.showDialog(null);
directory_text.setText(file.getAbsolutePath());

}

public void Export(ActionEvent e) {

pg.setProgress(-1);
foo();
Alert alert = new Alert(AlertType.INFORMATION, "Spreadsheet Generated", ButtonType.CLOSE);
alert.showAndWait();
pg.setProgress(1);
}

上面的 Export() 方法在单击按钮时执行时,似乎不按顺序运行方法语句。直到弹出警报窗口后才会显示进度条动画。我该如何纠正这个问题?

最佳答案

假设您的 foo() 方法需要很长时间才能运行,所发生的情况是您阻塞了 FX 应用程序线程,这会阻止它执行其通常的职责,例如渲染 UI 。因此,虽然语句(当然)按照您编写的顺序执行,即 pgprogressProperty 设置为 -1,那么执行 foo(),然后显示 Alert,在整个过程之前,您实际上不会在 UI 中看到这些结果完成(或者,实际上,在这种情况下,直到您通过调用 showAndWait() 放弃对 FX 应用程序线程的控制)。

解决这个问题的基本方法是在后台线程中运行foo()。如果您希望在完成时执行与 UI 相关的代码,则最好的方法是使用 Task并使用其 onSucceeded 处理程序在最后执行 UI 代码。所以一般来说你会做这样的事情:

public void Export(ActionEvent e) {

pg.setProgress(-1);
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
foo();
return null ;
}
};
task.setOnSucceeded(evt -> {
Alert alert = new Alert(AlertType.INFORMATION, "Spreadsheet Generated", ButtonType.CLOSE);
alert.showAndWait();
pg.setProgress(1);

});
new Thread(task).start();
}

关于JavaFX Action 事件语句执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45684759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com