在JavaFX应用程序中,我希望根据我在另一个类中实现的一些工作逻辑来更新状态栏。
我无法弄清楚如何结合我的意愿,将工作逻辑传递给方法(而不是将其写在任务中)并了解工作进度百分比。
这是带有Task的控制器的示例:
public class FXMLDocumentController implements Initializable { @FXML private Label label; @FXML ProgressBar progressBar; @FXML private void handleButtonAction(ActionEvent event) { ServicemyService = new Service () { @Override protected Task createTask() { return new Task () { @Override protected Void call() throws Exception { try { DatabaseFunctionality.performWorkOnDb(); //updateProgress(1, 1); } catch (InterruptedException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } return null; } }; } }; progressBar.progressProperty().bind(myService.progressProperty()); myService.restart(); } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } }
这是帮助程序类:
public class DatabaseFunctionality { public static void performWorkOnDb () throws InterruptedException { for (int i = 1; i <= 100; i++) { System.out.println("i=" + i); Thread.sleep(100); //Update progress } } }
谢谢
您在这里有几个选择。一种方法是按照Uluk的建议进行操作,并在您的DatabaseFunctionality
课堂上公开一个可观察的属性:
public class DatabaseFunctionality { private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper(); public double getProgress() { return progressProperty().get(); } public ReadOnlyDoubleProperty progressProperty() { return progress ; } public void performWorkOnDb() throws Exception { for (int i = 1; i <= 100; i++) { System.out.println("i=" + i); Thread.sleep(100); progress.set(1.0*i / 100); } } }
现在,在您的中Task
,您可以观察该属性并更新任务的进度:
ServicemyService = new Service () { @Override protected Task createTask() { return new Task () { @Override protected Void call() throws Exception { try { DatabaseFunctionality dbFunc = new DatabaseFunctionality(); dbFunc.progressProperty().addListener((obs, oldProgress, newProgress) -> updateProgress(newProgress.doubleValue(), 1)); dbaseFunc.performWorkOnDb(); } catch (InterruptedException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } return null; } }; } };
另一个选择(如果您不希望数据访问对象依赖于JavaFX属性API)是向数据访问对象传递回调以更新进度。A BiConsumer
将为此工作:
public class DatabaseFunctionality { private BiConsumerprogressUpdate ; public void setProgressUpdate(BiConsumer progressUpdate) { this.progressUpdate = progressUpdate ; } public void performWorkOnDb() throws Exception { for (int i = 1; i <= 100; i++) { System.out.println("i=" + i); Thread.sleep(100); if (progressUpdate != null) { progressUpdate.accept(i, 100); } } } }
然后
ServicemyService = new Service () { @Override protected Task createTask() { return new Task () { @Override protected Void call() throws Exception { try { DatabaseFunctionality dbFunc = new DatabaseFunctionality(); dbFunc.setProgressUpdate((workDone, totalWork) -> updateProgress(workDone, totalWork)); dbaseFunc.performWorkOnDb(); } catch (InterruptedException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } return null; } }; } };