/** Función encargada de mostrar que se va a actualizar */ public void updateApp() { // Temporizador para mostrar el mensaje de inicio de la aplicación. Task wait = new Task<Boolean>() { @Override protected Boolean call() throws Exception { updateMessage(" . . . L O A D I N G . . . "); Thread.sleep(LONG_WAIT_IN_MILLIS); return null; } }; // Hacemos que la tarea pueda manejar el texto de la barra de estado del splash status.textProperty().bind(wait.messageProperty()); // Animación barra de estado. progressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS); // Cuando termine la espera llamamos a la función para revisar si existen actualizaciones. wait.setOnSucceeded(event -> checkforupdates()); // Creamos e iniciamos un hilo. new Thread(wait).start(); }
public void setTask(Task<?> task) { if (_task != null) { _task.cancel(); _animation.stop(); visibleProperty().unbind(); log.info("Task Canceled"); } _task = task; if (_task != null) { visibleProperty().bind(task.runningProperty()); _task .runningProperty() .addListener( o -> { SimpleBooleanProperty running = (SimpleBooleanProperty) o; if (running.get()) { _animation.play(); } else { _animation.stop(); } }); task.setOnFailed( e -> { log.error(_task.getMessage()); setTask(null); }); } }
private void showSplash( final Stage initStage, Task<?> task, InitCompletionHandler initCompletionHandler) { progressText.textProperty().bind(task.messageProperty()); loadProgress.progressProperty().bind(task.progressProperty()); task.stateProperty() .addListener( (observableValue, oldState, newState) -> { if (newState == Worker.State.SUCCEEDED) { loadProgress.progressProperty().unbind(); loadProgress.setProgress(1); initStage.toFront(); FadeTransition fadeSplash = new FadeTransition(Duration.seconds(1.2), splashLayout); fadeSplash.setFromValue(1.0); fadeSplash.setToValue(0.0); fadeSplash.setOnFinished(actionEvent -> initStage.hide()); fadeSplash.play(); initCompletionHandler.complete(); } // todo add code to gracefully handle other task states. }); Scene splashScene = new Scene(splashLayout); initStage.initStyle(StageStyle.UNDECORATED); final Rectangle2D bounds = Screen.getPrimary().getBounds(); initStage.setScene(splashScene); initStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2); initStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2); initStage.show(); }
@Override public void afterShow() { final boolean autostart = Boolean.parseBoolean(application.getParameters().getNamed().get("autostart")); if (autostart) { javafx.application.Platform.runLater( () -> { final Alert dialog = new Alert(AlertType.INFORMATION); dialog.initOwner(application.getPrimaryStage()); dialog.setHeaderText("Autostart in 10 seconds. Close this dialog to cancel"); dialog.show(); final Task<Void> sleeper = new Task<Void>() { @Override protected Void call() throws Exception { try { Thread.sleep(10000); } catch (final Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } return null; } }; sleeper.setOnSucceeded( event -> { if (dialog.isShowing()) { dialog.close(); startButton.fire(); } }); new Thread(sleeper, "autostartThread").start(); }); } }
@Override public void start(Stage primaryStage) throws Exception { // creating Layout final Group root = new Group(); Scene scene = new Scene(root, 400, 400); primaryStage.setScene(scene); primaryStage.setResizable(false); StackPane waitingPane = new StackPane(); final ProgressBar progress = new ProgressBar(); Label load = new Label("loading things..."); progress.setTranslateY(-25); load.setTranslateY(25); waitingPane.getChildren().addAll(new Rectangle(400, 400, Color.WHITE), load, progress); root.getChildren().add(waitingPane); // Task for computing the Panels: Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { for (int i = 0; i < 20; i++) { try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException ex) { ex.printStackTrace(); } final double prog = i * 0.05; Platform.runLater( new Runnable() { public void run() { progress.setProgress(prog); } }); } return null; } }; // stateProperty for Task: task.stateProperty() .addListener( new ChangeListener<Worker.State>() { @Override public void changed( ObservableValue<? extends State> observable, State oldValue, Worker.State newState) { if (newState == Worker.State.SUCCEEDED) { loadPanels(root); } } }); // start Task new Thread(task).start(); primaryStage.show(); }
ShowTweetsTask() { tweetsCreationTask = tweetSetData.getCreationTask(); tweetsUpdateTask = new TweetsUpdateTask(tweetSetData, wordle); tweetsSnapshotTask = new TweetsSnapshotTask(parents); setOnCancelled( e -> { tweetsCreationTask.cancel(); tweetsUpdateTask.cancel(); tweetsSnapshotTask.cancel(); }); }
protected void createAndUpdateFooter() { Task computeThread = new Task() { @Override protected Object call() throws Exception { Set<SipPreview> sipPreviews = new HashSet<>(); for (TreeItem<String> item : input) { if (item instanceof SipPreviewNode) { sipPreviews.add(((SipPreviewNode) item).getSip()); } else if (item instanceof SchemaNode) { sipPreviews.addAll(((SchemaNode) item).getSipPreviews().keySet()); } } sips = sipPreviews.size(); compute(sipPreviews); return null; } }; computeThread.setOnSucceeded( event -> { if (input.size() == 1) { TreeItem item = input.get(0); if (item == null) { Footer.setClassPlanStatus(""); return; } sb.append(item.getValue()).append(": "); if (item instanceof SipPreviewNode) { sb.append(representations).append(" ").append("reps"); sb.append(", "); } else { sb.append(sips).append(" SIP").append(", "); } } else { sb.append(input.size()).append(" ").append(I18n.t("items")).append(": "); sb.append(sips).append(" SIP").append(", "); } sb.append(folders).append(" ").append(I18n.t("folders")); sb.append(", "); sb.append(files).append(" ").append(I18n.t("files")); sb.append(", "); sb.append(Utils.formatSize(size)); Footer.setClassPlanStatus(sb.toString()); }); new Thread(computeThread).start(); }
/** * Do import for the specified type and file name. * * @param modelType the model type * @param fileName the file name */ public void doImport(InformationModelType modelType, final String fileName) { Preconditions.checkNotNull(modelType); Preconditions.checkNotNull(fileName); // Make sure in application thread. FxUtils.checkFxUserThread(); // Update UI. modelTypeLabel.setText(modelType.getDisplayName()); fileNameLabel.setText(fileName); // Instantiate appropriate importer class. ImportHandler importHandler = null; switch (modelType) { case CEM: importHandler = new CEMImporter(); break; case HeD: importHandler = new HeDImporter(); break; case FHIM: importHandler = new FHIMImporter(); break; default: throw new UnsupportedOperationException( modelType.getDisplayName() + " import not yet supported in ISAAC."); } // Do work in background. Task<InformationModel> task = new ImporterTask(fileName, importHandler); // Bind cursor to task state. ObjectBinding<Cursor> cursorBinding = Bindings.when(task.runningProperty()).then(Cursor.WAIT).otherwise(Cursor.DEFAULT); this.getScene().cursorProperty().bind(cursorBinding); Thread t = new Thread(task, "Importer_" + modelType); t.setDaemon(true); t.start(); }
public EventPopoverPage(final DataService dataService, final Event event, boolean showBack) { this.showBack = showBack; getStyleClass().add("event-popover-page"); final Session session = event.getSession(); scrollPane = new ScrollPane(); scrollPane.setFitToWidth(true); scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); content = session == null ? new EventContent(event, dataService) : new SessionContent(session, event, dataService); scrollPane.setContent(content); getChildren().add(scrollPane); if (CHECK_AVAIL_TASK != null) { CHECK_AVAIL_TASK.cancel(); } if (!ConferenceScheduleApp.getInstance().getSessionManagement().isGuestProperty().get() && content instanceof SessionContent) { CHECK_AVAIL_TASK = dataService.checkAvailability(event); CHECK_AVAIL_TASK.setOnSucceeded( new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent event) { final SessionContent sc = (SessionContent) content; final Availability avail = CHECK_AVAIL_TASK.getValue(); if (!sc.fav) { sc.button.setText(avail.full ? "Session Full" : "Register"); full.set(avail.full); } } }); FILTER_EXECUTOR.submit(CHECK_AVAIL_TASK); } }
private void bindTaskToControl(ServiceAndTask demoControl, Task<String> task) { demoControl.startTask.setOnMouseClicked((val) -> new Thread(task).start()); demoControl.labelTask.textProperty().bind(task.messageProperty()); task.addEventHandler( WorkerStateEvent.WORKER_STATE_SUCCEEDED, (val) -> { try { demoControl.labelTask.textProperty().unbind(); demoControl.labelTask.setText(task.get()); demoControl.startTask.setDisable(true); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }); demoControl.progressTask.progressProperty().bind(task.progressProperty()); }
public Status() { super(); _icon = GlyphRegistry.get(AwesomeIcon.REFRESH, "10px"); getChildren().add(_icon); _animation = new RotateTransition(Duration.millis(500), _icon); _animation.setFromAngle(0); _animation.setByAngle(360); _animation.setCycleCount(Animation.INDEFINITE); _animation.setInterpolator(Interpolator.LINEAR); setVisible(false); setOnMouseClicked(e -> _task.cancel()); }
public void handle(ActionEvent t) { nowLoading(); Task<String> task = new Task<String>() { @Override protected String call() throws Exception { return restoFXClient.getMenu(); } }; task.setOnSucceeded( new EventHandler<WorkerStateEvent>() { public void handle(WorkerStateEvent success) { String menu = (String) success.getSource().getValue(); System.out.println(menu); text.setText(formatJsonString(menu)); nowLoaded(); } }); new Thread(task, "Fetch Menu Thread").start(); }
/** Función encargada de Mostrar la finalización de la actividad. */ private void showFinishProgress(Task onFinishTask) { // Timer que se encarga de mostrar un progreso de 0 a 100 en 1 segundo. Task progress = new Task() { @Override protected Object call() throws Exception { for (int i = 0; i <= 100; i++) { updateProgress(i, 100); Thread.sleep(10); } return null; } }; // Mostramos que terminó la descarga en la barra de progreso progressBar.progressProperty().bind(progress.progressProperty()); // Cuando termina ese progreso, llamamos a la función que se desea llamar después. progress.setOnSucceeded(event2 -> new Thread(onFinishTask).start()); new Thread(progress).start(); }
public static void showTaskProgressDialog( Window ownerWindow, Task task, boolean showTaskMessage) { final Stage dialog = new Stage(); task.setOnSucceeded(event -> dialog.close()); task.setOnCancelled(event -> dialog.close()); dialog.initStyle(StageStyle.UTILITY); dialog.initModality(Modality.APPLICATION_MODAL); dialog.initOwner(ownerWindow); dialog.titleProperty().bind(task.titleProperty()); // dialog.setTitle(ResourceManager.getMessage("title.dialog.processing")); dialog.setOnCloseRequest( event -> Logger.getLogger(Dialogs.class) .info(ResourceManager.getMessage("notification.task.terminatedByUser"))); ProgressBar progressBar = new ProgressBar(0); progressBar.progressProperty().bind(task.progressProperty()); progressBar.setMaxWidth(Double.MAX_VALUE); progressBar.getStyleClass().add("dark"); Label label = new Label(ResourceManager.getMessage("label.pleaseWaitWhile")); Label taskMessage = new Label(); taskMessage.textProperty().bind(task.messageProperty()); Button cancelButton = new Button(ResourceManager.getMessage("label.button.cancel")); cancelButton.setOnAction( event -> { task.cancel(); Logger.getLogger(Dialogs.class) .info(ResourceManager.getMessage("notification.task.terminatedByUser")); }); ButtonBar buttonBar = new ButtonBar(); buttonBar.getButtons().add(cancelButton); VBox dialogVBox = new VBox(); dialogVBox.setFillWidth(true); dialogVBox.setSpacing(5); dialogVBox.setPadding(new Insets(5)); dialogVBox.setPrefSize(300, VBox.USE_COMPUTED_SIZE); dialogVBox.getChildren().add(label); if (showTaskMessage) { dialogVBox.getChildren().add(taskMessage); } dialogVBox.getChildren().add(progressBar); dialogVBox.getChildren().add(buttonBar); Scene dialogScene = new Scene(dialogVBox); dialogScene.getStylesheets().add(ResourceManager.getUIThemeStyle()); dialog.setScene(dialogScene); dialog.setResizable(false); dialog.show(); }
public TaskProgressIndicator(Task<?> task) { this(); label.textProperty().bind(task.messageProperty()); progress.progressProperty().bind(task.progressProperty()); }
/** Función encargada de revisar si existen actualizaciones. */ private void checkforupdates() { /** * Esta Función descarga un archivo txt que contiene la información y enlace de descarga de las * distintas versiones de la aplicación, compara la versión del programa y si encuentra una * versión mas reciente en el archivo manda llamar a la función de descarga. */ // Tarea encargada de revisar si hay actualización. checkupdates = new Task<String>() { @Override protected String call() throws Exception { // Avisamos al usuario que se van a revisar las actualziaciones. updateMessage("CHECKING FOR UPDATES"); Thread.sleep(500); // Creamos una dirección para el archivo de texto. URL updatefile = new URL(UPDATE_TXT); // Si existe el archivo de texto. if (updatefile != null) { // Creamos un lector. BufferedReader in = new BufferedReader(new InputStreamReader(updatefile.openStream())); // Buffer. String str; // Para cada linea. while ((str = in.readLine()) != null) { // Partimos cada linea "repositorio; version; URL" notese que el separador es "; " String[] buf = str.split("; "); // Si la versión es mayor y el repositorio corresponde entonces preguntamos si se // desea descargar. if ((Double.parseDouble(buf[1]) > VERSION) && (buf[0].equalsIgnoreCase(REPOSITORY))) { updateMessage( " A NEW VERSION OF TRUDISP IS AVAILABLE\n V_: " + buf[1] + "\n DOWNLOAD?"); isupdating = true; return buf[2]; } else { isupdating = false; } } } else // No se ha podido establecer conexión con el archivo de texto. { updateMessage("CONNECTION ERROR"); Thread.sleep(SHORT_WAIT_MILLIS); isupdating = false; cancel(); } return null; } }; // Permitimos que la tarea maneje los mensajes de la barra de estado. status.textProperty().bind(checkupdates.messageProperty()); // Si se ha terminado la tarea checkupdates.setOnSucceeded( event -> { if (isupdating) { // Agregamos los botones de control. splashLayout.getChildren().add(updateLayout); splashStage.sizeToScene(); progressBar.setProgress(0); } else { // Cerramos el splash y avisamos que se ha terminado. splashStage.close(); isready.set(true); } }); // Si ha fallado latarea. checkupdates.setOnFailed( event -> { splashStage.close(); isready.set(true); }); // Creamos e iniciamos el hilo. new Thread(checkupdates).start(); }
public void stopTask() { nfc.cancel(); task.cancel(); }
/** Función encargada de descargar la actualización */ private void downloadupdate() { // El usuario aceptó la actualización entonces se le pide seleccione un directirio para guardar final File file = new DirectoryChooser().showDialog(splashStage); // Creamos el archivo para escribir. final File filetowrite = new File(file.getAbsolutePath() + "/" + FILE_NAME); // Eliminamos los botones de control. splashLayout.getChildren().remove(updateLayout); // Animamos la barra de progreso. progressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS); // Tarea encargada de realizar la descarga. Task download = new Task() { @Override protected Object call() throws Exception { updateMessage(". . . D O W N L O A D I N G . . "); // Creamos el objeto que contendrá el enlace. URL source = new URL(checkupdates.get()); if (source != null) { // Copiamos el arhcivo del enlace. Files.copy( source.openStream(), filetowrite.toPath(), StandardCopyOption.REPLACE_EXISTING); updateMessage(" READY "); Thread.sleep(SHORT_WAIT_MILLIS); } else { cancel(); } return null; } }; // Permitimos que la tarea maneje el texto del splash status.textProperty().bind(download.messageProperty()); // Si se ha terminado la descarga. download.setOnSucceeded( event -> { // Tarea encargada de mostrar que se a terminado la descarga. Task timer = new Task() { @Override protected Object call() throws Exception { updateMessage("PLEASE START THE NEW VERSION"); Thread.sleep(SHORT_WAIT_MILLIS); return null; } }; // Permitimos que la tarea maneje el texto del splash status.textProperty().bind(timer.messageProperty()); // cuando termine la tarea cerramos la aplicación. timer.setOnSucceeded(event1 -> System.exit(0)); // Mostramos animación de la barra de progreso. showFinishProgress(timer); }); // Si ha fallado la descarga. download.setOnFailed( event -> { // Tarea encargada de mostrar que ha fallado la descarga. Task timer = new Task() { @Override protected Object call() throws Exception { updateMessage("Descarga Fallida"); Thread.sleep(SHORT_WAIT_MILLIS); return null; } }; // Permitimos que la tarea maneje el texto del splash status.textProperty().bind(timer.messageProperty()); timer.setOnSucceeded( event1 -> { splashStage.close(); isready.set(true); }); // Mostramos animación de la barra de progreso. showFinishProgress(timer); }); // Creamos el hilo y lo iniciamos. new Thread(download).start(); }
public void connectMyo() { try { LOGGER.info("Connecting to Myo"); updateMyoStatus("Attempting to find a Myo..."); Myo myo = hub.waitForMyo(10000); if (myo == null) { LOGGER.error("Unable to connect to Myo"); throw new RuntimeException("Unable to find a Myo!"); } myo.setStreamEmg(StreamEmgType.STREAM_EMG_ENABLED); LOGGER.info("EMG Stream enabled"); updateMyoStatus("Connected to a Myo armband!"); jsonDataCollector = new JsonDataCollector(); jsonDataCollector.addListsner(new FileMyoDataCollector("c:\\tmp\\myo")); jsonDataCollector.addListsner(new SocketServerCollector()); hub.addListener(jsonDataCollector); LOGGER.info("Listener added"); indicatorMyo.setIndicatorStyle(SimpleIndicator.IndicatorStyle.GREEN); startButton.setDisable(false); startButton.setDefaultButton(true); Task<ObservableList<String>> task = new Task<ObservableList<String>>() { @Override protected ObservableList<String> call() throws Exception { while (true) { List<RecordListener> collect = jsonDataCollector .getListeners() .stream() .filter(s -> s instanceof SocketServerCollector) .collect(Collectors.toList()); List<String> connections = collect .stream() .map(s -> ((SocketServerCollector) s).channels) .flatMap(c -> c.stream().map(f -> mapRemoteAddress(f))) .collect(Collectors.toList()); updateValue(FXCollections.observableList(connections)); Thread.sleep(10); } } }; Task<Boolean> booleanTask = new Task<Boolean>() { @Override protected Boolean call() throws Exception { while (true) { List<RecordListener> collect = jsonDataCollector .getListeners() .stream() .filter(s -> s instanceof SocketServerCollector) .collect(Collectors.toList()); long count = collect .stream() .map(s -> ((SocketServerCollector) s).channels) .flatMap(Collection::stream) .filter(AsynchronousSocketChannel::isOpen) .count(); updateValue(count > 0 ? Boolean.TRUE : Boolean.FALSE); Thread.sleep(10); } } }; Task<SimpleIndicator.IndicatorStyle> stringTask = new Task<SimpleIndicator.IndicatorStyle>() { @Override protected SimpleIndicator.IndicatorStyle call() throws Exception { while (true) { List<RecordListener> collect = jsonDataCollector .getListeners() .stream() .filter(s -> s instanceof SocketServerCollector) .collect(Collectors.toList()); long count = collect .stream() .map(s -> ((SocketServerCollector) s).channels) .flatMap(Collection::stream) .filter(AsynchronousSocketChannel::isOpen) .count(); updateValue( count > 0 ? SimpleIndicator.IndicatorStyle.RED : SimpleIndicator.IndicatorStyle.GREEN); Thread.sleep(10); } } }; inboundConnections.itemsProperty().bind(task.valueProperty()); indicatorServer.onProperty().bind(booleanTask.valueProperty()); // try { // indicatorServer.indicatorStyleProperty().bind(stringTask.valueProperty()); // } catch (Throwable e) { // //??Throws a null ppointer but it works?? // } Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); Thread thread2 = new Thread(booleanTask); thread2.setDaemon(true); thread2.start(); Thread thread3 = new Thread(stringTask); thread3.setDaemon(true); thread3.start(); } catch (Exception e) { e.printStackTrace(); updateMyoStatus("Error: " + e.getMessage()); } }