我正在使用 JavaFx 创建 Java 独立应用程序。
我看过一些示例,但我无法理解如何在我的代码场景中使用 javaFX Task
。
这是我为我从 SceneBuilder 设置的按钮 onAction 调用的 Controller 函数 -->
public class MainScreenController {
@FXML
private JFXButton btnSelectImg;
@FXML
private ImageView imageViewObj;
@FXML
private ProgressBar progressBarObj;
//..
//..
@FXML
private void onFileSelectButtonClick() {
//Some Operations are carried out
//..
//Then I want to set Image in ImageView
imageViewObj.setImage(myImage);
// Some Code Here
//..
// Set Progress
progressBarObj.setProgress(0.1);
// Some Code Here
//..
// Set Progress
progressBarObj.setProgress(0.2);
//...
//...
// Maybe change some other Controls
//..........
}
//..
//..
}
现在,随着代码一步步进行,我逐渐更新同一函数中的多个控件,但最终在执行完成时更新。
我想在执行时更新控件,如代码所示。
最佳答案
这可能与其他问题重复:
- JavaFx: Update UI label asynchronously with messages while application different methods execution
- JavaFx ProgressBar doesnt update
- Platform.runLater and Task in JavaFX
- Usage of JavaFX Platform.runLater and access to UI from a different thread
也许还有其他一些问题。
<小时/>作为总体方法,您定义一个任务,然后在任务的执行主体中,利用 Platform.runLater()、updateProgress() 和其他机制来实现您所需要的。有关这些机制的进一步说明,请参阅相关问题。
final ImageView imageViewObj = new ImageView();
Task<Void> task = new Task<Void>() {
@Override protected Void call() throws Exception {
//Some Operations are carried out
//..
//Then I want to set Image in ImageView
// use Platform.runLater()
Platform.runLater(() -> imageViewObj.setImage(myImage));
// Some Code Here
//..
// Set Progress
updateProgress(0.1, 1);
// Some Code Here
//..
// Set Progress
updateProgress(0.2, 1);
int variable = 2;
final int immutable = variable;
// Maybe change some other Controls
// run whatever block that updates the controls within a Platform.runLater block.
Platform.runLater(() -> {
// execute the control update logic here...
// be careful of updating control state based upon mutable data in the task thread.
// instead only use immutable data within the runLater block (avoids race conditions).
});
variable++;
// some more logic related to the changing variable.
return null;
}
};
ProgressBar updProg = new ProgressBar();
updProg.progressProperty().bind(task.progressProperty());
Thread thread = new Thread(task, "my-important-stuff-thread");
thread.setDaemon(true);
thread.start();
关于java - 运行应用程序时更新 JavaFX 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42659003/