ciao!
continuando un pò lo studio di javafx, vorrei lanciare dei task in background, e visualizzare un loading dialog durante il processo.
mi sono spulicato un pò di esempi e documentazione, e sono arrivato a questo:
dal controller:codice:public class LoadingDialog { private final Stage dialogStage; private final ProgressBar progressBar = new ProgressBar(); private final ProgressIndicator progressIndicator = new ProgressIndicator(); public LoadingDialog() { dialogStage = new Stage(); dialogStage.initStyle(StageStyle.DECORATED); dialogStage.setResizable(false); dialogStage.initModality(Modality.APPLICATION_MODAL); dialogStage.setTitle("LOADING"); final Label label = new Label(); label.setText("Please wait..."); //progressBar.setProgress(-1F); progressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS); //progressIndicator.setProgress(-1F); progressIndicator.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS); final HBox hb = new HBox(); hb.setSpacing(5); hb.setAlignment(Pos.CENTER); hb.getChildren().addAll(progressBar, progressIndicator); Scene scene = new Scene(hb); dialogStage.setScene(scene); } public void activateProgressBar(final Task task) throws InterruptedException { progressBar.progressProperty().bind(task.progressProperty()); progressIndicator.progressProperty().bind(task.progressProperty()); dialogStage.show(); } public Stage getDialogStage() { return dialogStage; } }
funzionare, funziona.codice:public class ControllerUno { @FXML Button btnTest; @FXML private void onBtnClicked() throws InterruptedException { LoadingDialog loadingDialog = new LoadingDialog(); Task<Void> task = new Task<Void>() { @Override public Void call() throws InterruptedException { // DO STUFF return null; } }; loadingDialog.activateProgressBar(task); task.setOnSucceeded(event -> { loadingDialog.getDialogStage().close(); }); task.setOnCancelled(event -> { loadingDialog.getDialogStage().close(); }); loadingDialog.getDialogStage().show(); Thread thread = new Thread(task); thread.start(); } }
volevo capire se è anche corretto come modo di procedere.
o come eventualmente posso migliorare il codice!

Rispondi quotando