javafx.scene.control.cell.ComboBoxTableCell#javafx.concurrent.Task源码实例Demo

下面列出了javafx.scene.control.cell.ComboBoxTableCell#javafx.concurrent.Task 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: java-ml-projects   文件: AppUtils.java
/**
 * 
 * Perform an async call
 * 
 * @param action
 * @param success
 * @param error
 */
public static <T extends Object> void doAsyncWork(Supplier<T> action, Consumer<T> success,
		Consumer<Throwable> error) {
	Task<T> tarefaCargaPg = new Task<T>() {
		@Override
		protected T call() throws Exception {
			return action.get();
		}

		@Override
		protected void succeeded() {
			success.accept(getValue());
		}

		@Override
		protected void failed() {
			error.accept(getException());
		}
	};
	Thread t = new Thread(tarefaCargaPg);
	t.setDaemon(true);
	t.start();
}
 
源代码2 项目: gluon-samples   文件: TrainingView.java
public TrainingView() {

        label = new Label();

        Button button = new Button("train network model");
        button.setOnAction(e -> {
            Task task = train();
            button.disableProperty().bind(task.runningProperty());
        });
        series = new Series();
        series.setName("#iterations");
        Chart chart = createChart(series);

        VBox controls = new VBox(15.0, label, button, chart);
        controls.setAlignment(Pos.CENTER);

        setCenter(controls);
    }
 
源代码3 项目: megan-ce   文件: IntervalTree4Matches.java
/**
 * selects the matches to keep for a given read and puts them into an interval tree
 *
 * @param readBlock
 * @param task      can be null
 * @param progress
 * @return interval tree
 */
public static IntervalTree<IMatchBlock> computeIntervalTree(IReadBlock readBlock, Task task, ProgressListener progress) throws CanceledException {
    final IntervalTree<IMatchBlock> intervalTree = new IntervalTree<>();

    if (progress != null) {
        progress.setMaximum(readBlock.getNumberOfAvailableMatchBlocks());
        progress.setProgress(0);
    }

    for (int m = 0; m < readBlock.getNumberOfAvailableMatchBlocks(); m++) {
        final IMatchBlock matchBlock = readBlock.getMatchBlock(m);
        intervalTree.add(new Interval<>(matchBlock.getAlignedQueryStart(), matchBlock.getAlignedQueryEnd(), matchBlock));
        if (task != null && task.isCancelled())
            break;
        if (progress != null)
            progress.incrementProgress();
    }
    return intervalTree;
}
 
源代码4 项目: JavaFX-Chat   文件: ChatController.java
public synchronized void addAsServer(Message msg) {
    Task<HBox> task = new Task<HBox>() {
        @Override
        public HBox call() throws Exception {
            BubbledLabel bl6 = new BubbledLabel();
            bl6.setText(msg.getMsg());
            bl6.setBackground(new Background(new BackgroundFill(Color.ALICEBLUE,
                    null, null)));
            HBox x = new HBox();
            bl6.setBubbleSpec(BubbleSpec.FACE_BOTTOM);
            x.setAlignment(Pos.CENTER);
            x.getChildren().addAll(bl6);
            return x;
        }
    };
    task.setOnSucceeded(event -> {
        chatPane.getItems().add(task.getValue());
    });

    Thread t = new Thread(task);
    t.setDaemon(true);
    t.start();
}
 
源代码5 项目: Jupiter   文件: Simulator.java
/** Resets simulation. */
@FXML protected synchronized void reset() {
  Thread th = new Thread(new Task<Void>() {
    /** {@inheritDoc} */
    @Override
    public Void call() {
      mainController.clearConsole();
      history.reset();
      program.getState().reset();
      program.load();
      updateMemoryCells();
      updateCacheOrganization();
      refreshSim();
      scroll();
      Globals.PRINT = false;
      Status.EXIT.set(false);
      Status.EMPTY.set(true);
      return null;
    }
  });
  th.setDaemon(true);
  th.start();
}
 
源代码6 项目: OEE-Designer   文件: OpcUaTrendController.java
@Override
protected Task<String> createTask() {
	return new Task<String>() {

		@Override
		protected String call() throws Exception {
			String errorMessage = NO_ERROR;

			try {
				// resolve the input value into a reason
				Object javaValue = UaOpcClient.getJavaObject(dataValue.getValue());
				DateTime dt = dataValue.getServerTime();
				OffsetDateTime odt = DomainUtils.localTimeFromDateTime(dt);

				trendChartController.invokeResolver(getApp().getAppContext(), javaValue, odt, null);
			} catch (Exception e) {
				errorMessage = e.getMessage();

				if (errorMessage == null) {
					errorMessage = getClass().getSimpleName();
				}
			}
			return errorMessage;
		}
	};
}
 
源代码7 项目: OEE-Designer   文件: OpcDaTrendController.java
@Override
protected Task<String> createTask() {
	return new Task<String>() {

		@Override
		protected String call() throws Exception {
			String errorMessage = NO_ERROR;

			try {
				// resolve the input value into a reason
				OpcDaVariant varientValue = item.getValue();
				Object value = varientValue.getValueAsObject();

				trendChartController.invokeResolver(getApp().getAppContext(), value, item.getLocalTimestamp(),
						null);
			} catch (Exception e) {
				errorMessage = e.getMessage();
			}
			return errorMessage;
		}
	};
}
 
源代码8 项目: OEE-Designer   文件: HttpTrendController.java
@Override
protected Task<Void> createTask() {
	return new Task<Void>() {

		@Override
		protected Void call() {
			try {
				trendChartController.invokeResolver(getApp().getAppContext(), dataValue, timestamp, reason);
			} catch (Exception e) {
				Platform.runLater(() -> {
					AppUtils.showErrorDialog(e);
				});
			}
			return null;
		}
	};
}
 
源代码9 项目: OEE-Designer   文件: OeeApplication.java
@Override
public void start(Stage primaryStage) throws Exception {
	final Task<String> startTask = new Task<String>() {
		@Override
		protected String call() throws Exception {
			// wait for a database connection by requesting an EntityManager
			PersistenceService.instance().getEntityManager();
			return getClass().getSimpleName();
		}
	};

	// start the database connection
	new Thread(startTask).start();

	// show the dialog and show the main stage when done
	showSplash(primaryStage, startTask, () -> showMainStage(null));
}
 
源代码10 项目: DevToolBox   文件: MainAction.java
public void pageSizeBoxChangeForValueAction() {
    try {
        DialogUtil.showDialog(mc.pane.getScene().getWindow());
        new Thread(new Task() {
            @Override
            protected Object call() throws Exception {
                mc.paginationForValue.getPageFactory().call(0);
                DialogUtil.close();
                return null;
            }

            @Override
            protected void setException(Throwable t) {
                super.setException(t);
                LOGGER.error("获取redis分页数据异常", t);
                Toast.makeText("获取redis信息异常" + t.getLocalizedMessage()).show(mc.pane.getScene().getWindow());
                DialogUtil.close();
            }
        }).start();
    } catch (Exception ex) {
        Toast.makeText("获取redis信息异常" + ex.getLocalizedMessage()).show(mc.pane.getScene().getWindow());
        LOGGER.error("获取redis信息异常", ex);
        DialogUtil.close();
    }
}
 
源代码11 项目: neural-style-gui   文件: AsyncImageProperty.java
@Override
protected Task<Image> createTask() {
    final File imageFile = this.imageFile;
    final int width = this.width;
    final int height = this.height;
    return new Task<Image>() {
        @Override
        protected Image call() {
            try {
                return new Image(new FileInputStream(imageFile), width, height, true, false);
            } catch (IOException e) {
                log.log(Level.SEVERE, e.toString(), e);
                return null;
            }
        }
    };
}
 
源代码12 项目: tutorials   文件: SearchController.java
private void loadData() {

        String searchText = searchField.getText();

        Task<ObservableList<Person>> task = new Task<ObservableList<Person>>() {
            @Override
            protected ObservableList<Person> call() throws Exception {
                updateMessage("Loading data");
                return FXCollections.observableArrayList(masterData
                        .stream()
                        .filter(value -> value.getName().toLowerCase().contains(searchText))
                        .collect(Collectors.toList()));
            }
        };

        task.setOnSucceeded(event -> {
            masterData = task.getValue();
            pagination.setVisible(true);
            pagination.setPageCount(masterData.size() / PAGE_ITEMS_COUNT);
        });

        Thread th = new Thread(task);
        th.setDaemon(true);
        th.start();
    }
 
源代码13 项目: FXTutorials   文件: DownloaderApp.java
private Parent createContent() {
    VBox root = new VBox();
    root.setPrefSize(400, 600);

    TextField fieldURL = new TextField();
    root.getChildren().addAll(fieldURL);

    fieldURL.setOnAction(event -> {
        Task<Void> task = new DownloadTask(fieldURL.getText());
        ProgressBar progressBar = new ProgressBar();
        progressBar.setPrefWidth(350);
        progressBar.progressProperty().bind(task.progressProperty());
        root.getChildren().add(progressBar);

        fieldURL.clear();

        Thread thread = new Thread(task);
        thread.setDaemon(true);
        thread.start();
    });

    return root;
}
 
源代码14 项目: trex-stateless-gui   文件: PktCaptureService.java
@Override
protected Task<CapturedPackets> createTask() {
    return new Task<CapturedPackets>() {
        @Override
        protected CapturedPackets call() throws Exception {
            if (currentActiveMonitorId == 0) {
                return null;
            }
            try {
                return fetchCapturedPkts(currentActiveMonitorId, 10);
            } catch (PktCaptureServiceException e) {
                LOG.error("Unable to fetch pkts from monitor.", e);
                return null;
            }
        }
    };
}
 
源代码15 项目: FXyzLib   文件: ClothMesh.java
@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            updateTimer();
            
            IntStream.range(0, getIterations()).forEach(i->{});
            points.parallelStream().filter(p->{return points.indexOf(p) % (getDivisionsX() - 1) == 0;}).forEach(p -> {
                p.applyForce(new Point3D(5,-1,1));
            });
            for (int i = 0; i < getConstraintAccuracy(); i++) {
                points.parallelStream().forEach(WeightedPoint::solveConstraints);
            }
            points.parallelStream().forEach(p -> {
                p.applyForce(new Point3D(4.8f,1,-1));
                p.updatePhysics(deltaTime, 1);                        
            });

            return null;
        }
    };
}
 
源代码16 项目: AsciidocFX   文件: ThreadService.java
public <T> Future<?> runTaskLater(Runnable runnable) {

        Task<T> task = new Task<T>() {
            @Override
            protected T call() throws Exception {
                runnable.run();
                return null;
            }
        };

        task.exceptionProperty().addListener((observable, oldValue, newValue) -> {
            if (Objects.nonNull(newValue)) {
                newValue.printStackTrace();
            }
        });

        return threadPollWorker.submit(task);
    }
 
源代码17 项目: MyBox   文件: WeiboSnapRunController.java
protected void saveHtml(final String filename, final String contents) {
    if (filename == null || contents == null) {
        return;
    }
    Task<Void> saveHtmlTask = new Task<Void>() {
        @Override
        protected Void call() {
            try {
                try ( BufferedWriter out = new BufferedWriter(new FileWriter(filename, Charset.forName("utf-8"), false))) {
                    out.write(contents);
                    out.flush();
                    savedHtmlCount++;
                }
            } catch (Exception e) {
                loadFailed = true;
                errorString = e.toString();
            }
            return null;
        }
    };
    new Thread(saveHtmlTask).start();
}
 
源代码18 项目: trex-stateless-gui   文件: PGIDStatsService.java
@Override
protected Task<PGIdStatsRPCResult> createTask() {
    return new Task<PGIdStatsRPCResult>() {
        @Override
        protected PGIdStatsRPCResult call() {
            // TODO: remove when ConnectionManager.isConnected will be returns valid result
            if (ConnectionManager.getInstance().getApiH() == null) {
                return null;
            }

            PGIdStatsRPCResult pgIDStats = null;
            try {
                synchronized (lock) {
                    pgIDStats = RPCCommands.getPGIdStats(new ArrayList<>(pgIDs));
                }
            } catch (Exception exc) {
                LOG.error("Failed to get PGID stats", exc);
            }

            return pgIDStats;
        }
    };
}
 
源代码19 项目: old-mzmine3   文件: LocalMaxCentroidingModule.java
@Override
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
    @Nonnull Collection<Task<?>> tasks) {

  final RawDataFilesSelection rawDataFiles =
      parameters.getParameter(LocalMaxCentroidingParameters.dataFiles).getValue();
  final String suffix = parameters.getParameter(LocalMaxCentroidingParameters.suffix).getValue();

  if (rawDataFiles == null || rawDataFiles.getMatchingRawDataFiles().isEmpty()) {
    logger.warn("Centroiding module started with no raw data files selected");
    return;
  }

  for (RawDataFile rawDataFile : rawDataFiles.getMatchingRawDataFiles()) {

    // Create the data structures
    DataPointStore dataStore = DataPointStoreFactory.getTmpFileDataStore();

    final String newName = rawDataFile.getName() + " " + suffix;
    LocalMaximaCentroidingAlgorithm algorithm = new LocalMaximaCentroidingAlgorithm(dataStore);

    MSDKCentroidingMethod method = new MSDKCentroidingMethod(rawDataFile, algorithm, dataStore);

    MSDKTask newTask =
        new MSDKTask("Local maxima centroiding method", rawDataFile.getName(), method);

    // Add the feature table to the project
    newTask.setOnSucceeded(e -> {
      RawDataFile newRawFile = method.getResult();
      newRawFile.setName(newName);
      project.addFile(newRawFile);
    });

    // Add the task to the queue
    tasks.add(newTask);

  }

}
 
源代码20 项目: Recaf   文件: GuiController.java
/**
 * Asynchronously load a workspace from the given file.
 *
 * @param path
 * 		Path to workspace file.
 * @param action
 * 		Additional action to run with success/fail result.
 */
public void loadWorkspace(Path path, Consumer<Boolean> action) {
	Task<Boolean> loadTask = loadWorkspace(path);
	MainWindow main = windows.getMainWindow();
	loadTask.messageProperty().addListener((n, o, v) -> main.status(v));
	loadTask.setOnRunning(e -> {
		// Clear current items since we want to load a new workspace
		main.clear();
		main.disable(true);
	});
	loadTask.setOnSucceeded(e -> {
		// Load success
		main.disable(false);
		if (action != null)
			action.accept(true);
		// Update recently loaded
		config().backend().onLoad(path);
		main.getMenubar().updateRecent();
		// Updated cached primary jar to support recompile
		getWorkspace().writePrimaryJarToTemp();
	});
	loadTask.setOnFailed(e -> {
		// Load failure
		main.status("Failed to open file:\n" + path.getFileName());
		main.disable(false);
		if (action != null)
			action.accept(false);
	});
	ThreadUtil.run(loadTask);
}
 
源代码21 项目: chvote-1-0   文件: BallotDecryptionController.java
private void performBallotDecryption(BallotCipherService ballotCipherService, List<EncryptedBallotAndWrappedKey> encryptedBallots) {
    DecryptionService decryptionService = new DecryptionService(ballotCipherService, consoleOutputController);
    // Using a task here, so as to perform decryption without blocking the UI.
    Task<List<String>> ballotDecryptionTask = new BallotDecryptionTask(decryptionService, encryptedBallots);

    final Stopwatch ballotDecryption = Stopwatch.createStarted();

    // Handle success
    ballotDecryptionTask.setOnSucceeded(event -> {
        ballotDecryption.stop();
        consoleOutputController.logOnScreen(
                String.format(resources.getString("ballot_decryption.decryption_finished"),
                        formatElapsedTime(ballotDecryption)));

        consoleOutputController.progressMessage(String.format(resources.getString("ballot_decryption.invalid_ballots_text"), decryptionService.getInvalidCounter()));      //"Count of invalid ballots : " +
        saveCleartextBallots(ballotDecryptionTask.getValue());
        consoleOutputController.incrementStepCount();
    });

    // Handle failure
    ballotDecryptionTask.exceptionProperty().addListener((observable, oldValue, newException) -> {
        if (newException != null) {
            LOGGER.error(resources.getString("ballot_decryption.exception_occurred"), newException);
            consoleOutputController.logOnScreen(resources.getString("ballot_decryption.exception_occurred"), LogLevel.ERROR);
        }
    });

    // Start execution
    exec.execute(ballotDecryptionTask);
}
 
源代码22 项目: old-mzmine3   文件: BinningCentroidingModule.java
@Override
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
    @Nonnull Collection<Task<?>> tasks) {

  final RawDataFilesSelection rawDataFiles =
      parameters.getParameter(BinningCentroidingParameters.dataFiles).getValue();
  final Double binSize = parameters.getParameter(BinningCentroidingParameters.binSize).getValue();
  final String suffix = parameters.getParameter(BinningCentroidingParameters.suffix).getValue();

  if (rawDataFiles == null || rawDataFiles.getMatchingRawDataFiles().isEmpty()) {
    logger.warn("Centroiding module started with no raw data files selected");
    return;
  }

  for (RawDataFile rawDataFile : rawDataFiles.getMatchingRawDataFiles()) {

    // Create the data structures
    DataPointStore dataStore = DataPointStoreFactory.getTmpFileDataStore();

    final String newName = rawDataFile.getName() + " " + suffix;
    BinningCentroidingAlgorithm algorithm = new BinningCentroidingAlgorithm(dataStore, binSize);

    MSDKCentroidingMethod method = new MSDKCentroidingMethod(rawDataFile, algorithm, dataStore);

    MSDKTask newTask = new MSDKTask("Binning centroiding method", rawDataFile.getName(), method);

    // Add the feature table to the project
    newTask.setOnSucceeded(e -> {
      RawDataFile newRawFile = method.getResult();
      newRawFile.setName(newName);
      project.addFile(newRawFile);
    });

    // Add the task to the queue
    tasks.add(newTask);

  }

}
 
源代码23 项目: ns-usbloader   文件: TransferModule.java
TransferModule(DeviceHandle handler, LinkedHashMap<String, File> nspMap, Task<Void> task, LogPrinter printer){
    this.handlerNS = handler;
    this.nspMap = nspMap;
    this.task = task;
    this.logPrinter = printer;

    // Validate split files to be sure that there is no crap
    //logPrinter.print("TransferModule: Validating split files ...", EMsgType.INFO); // NOTE: Used for debug
    Iterator<Map.Entry<String, File>> iterator = nspMap.entrySet().iterator();
    while (iterator.hasNext()){
        File f = iterator.next().getValue();
        if (f.isDirectory()){
            File[] subFiles = f.listFiles((file, name) -> name.matches("[0-9]{2}"));
            if (subFiles == null || subFiles.length == 0) {
                logPrinter.print("TransferModule: Removing empty folder: " + f.getName(), EMsgType.WARNING);
                iterator.remove();
            }
            else {
                Arrays.sort(subFiles, Comparator.comparingInt(file -> Integer.parseInt(file.getName())));

                for (int i = subFiles.length - 2; i > 0 ; i--){
                    if (subFiles[i].length() < subFiles[i-1].length()) {
                        logPrinter.print("TransferModule: Removing strange split file: "+f.getName()+
                                "\n      (Chunk sizes of the split file are not the same, but has to be.)", EMsgType.WARNING);
                        iterator.remove();
                    } // what
                } // a
            } // nice
        } // stairway
    } // here =)
    //logPrinter.print("TransferModule: Validation complete.", EMsgType.INFO);  // NOTE: Used for debug
}
 
源代码24 项目: latexdraw   文件: LoadDrawingTest.java
private void configureLoadFile() {
	selectedFileName = "fooohfisuf_eyefd";
	task = Mockito.mock(Task.class);
	Mockito.when(file.canRead()).thenReturn(true);
	Mockito.when(file.getPath()).thenReturn("filepath");
	Mockito.when(openSaveManager.open("filepath", progressBar, statusWidget)).thenReturn(task);
	Mockito.when(openSaveManager.save(selectedFileName + ".svg", progressBar, statusWidget)).thenReturn(task);
	try {
		Mockito.when(task.get()).thenReturn(true);
	}catch(final InterruptedException | ExecutionException ex) {
		fail(ex.getMessage());
	}
}
 
源代码25 项目: milkman   文件: SynchManager.java
@Override
protected Task<SyncResult> createTask() {
	return new Task<SyncResult>() {

		@Override
		protected SyncResult call() throws Exception {
			try {
				synchronizer.synchronize(workspace);
				return new SyncResult(true, null);
			} catch (Throwable t) {
				log.warn("Failed to sync", t);
				return new SyncResult(false, t);
			}
		}};
}
 
源代码26 项目: trex-stateless-gui   文件: RecordController.java
@Override
protected Task<List<CaptureInfo>> createTask() {
    return new Task<List<CaptureInfo>>() {
        @Override
        protected List<CaptureInfo> call() throws Exception {
            try {
                return pktCaptureService.getActiveCaptures();
            } catch (PktCaptureServiceException e) {
                LOG.error("Unable to fetch pkts from monitor.", e);
                return null;
            }
        }
    };
}
 
源代码27 项目: mars-sim   文件: ProgressIndicatorTest2.java
@Override
public void start(Stage primaryStage) {
    StackPane root = new StackPane();
    ProgressIndicator pi = new ProgressIndicator();
    Task<Void> counter = new Task<Void>() {
        @Override
        public Void call() throws Exception {
            for (int i = 1; i <= 100; i++) {
                Thread.sleep(50);
                updateProgress(i, 100);
            }
            return null;
        }
    };
    pi.progressProperty().bind(counter.progressProperty());
    pi.progressProperty().addListener((obs, oldProgress, newProgress) -> {
        PseudoClass warning = PseudoClass.getPseudoClass("warning");
        PseudoClass critical = PseudoClass.getPseudoClass("critical");
        if (newProgress.doubleValue() < 0.3) {
            pi.pseudoClassStateChanged(warning, false);
            pi.pseudoClassStateChanged(critical, true);
        } else if (newProgress.doubleValue() < 0.65) {
            pi.pseudoClassStateChanged(warning, true);
            pi.pseudoClassStateChanged(critical, false);
        } else {
            pi.pseudoClassStateChanged(warning, false);
            pi.pseudoClassStateChanged(critical, false);
        }
    });
    pi.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
    root.setStyle("-fx-background-color: antiqueWhite;");
    root.getChildren().add(pi);
    Scene scene = new Scene(root, 400, 400);
    scene.getStylesheets().add("/css/progress.css");
    primaryStage.setScene(scene);
    primaryStage.show();
    new Thread(counter).start();
}
 
源代码28 项目: marathonv5   文件: TaskSample.java
public TaskSample() {
    TableView<DailySales> tableView = new TableView<DailySales>();
    Region veil = new Region();
    veil.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4)");
    ProgressIndicator p = new ProgressIndicator();
    p.setMaxSize(150, 150);
    //Define table columns
    TableColumn idCol = new TableColumn();
    idCol.setText("ID");
    idCol.setCellValueFactory(new PropertyValueFactory("dailySalesId"));
    tableView.getColumns().add(idCol);
    TableColumn qtyCol = new TableColumn();
    qtyCol.setText("Qty");
    qtyCol.setCellValueFactory(new PropertyValueFactory("quantity"));
    tableView.getColumns().add(qtyCol);
    TableColumn dateCol = new TableColumn();
    dateCol.setText("Date");
    dateCol.setCellValueFactory(new PropertyValueFactory("date"));
    dateCol.setMinWidth(240);
    tableView.getColumns().add(dateCol);
    StackPane stack = new StackPane();
    stack.getChildren().addAll(tableView, veil, p);

    // Use binding to be notified whenever the data source chagnes
    Task<ObservableList<DailySales>> task = new GetDailySalesTask();
    p.progressProperty().bind(task.progressProperty());
    veil.visibleProperty().bind(task.runningProperty());
    p.visibleProperty().bind(task.runningProperty());
    tableView.itemsProperty().bind(task.valueProperty());

    getChildren().add(stack);
    new Thread(task).start();
}
 
源代码29 项目: old-mzmine3   文件: AuditLogEntry.java
public AuditLogEntry(@Nonnull MZmineModule module, @Nonnull ParameterSet parameterSet,
    @Nonnull List<Task<?>> tasks) {
  this.module = module;
  this.parameterSet = parameterSet;

  for (Task<?> task : tasks) {
    AuditLogTaskRecord taskRecord = new AuditLogTaskRecord(task);
    taskRecords.add(taskRecord);
  }
}
 
源代码30 项目: gramophy   文件: Player.java
private void startUpdating()
{
    updaterThread = new Thread(new Task<Void>() {
        @Override
        protected Void call(){
            try
            {
                while(isActive)
                {
                    if(mediaPlayer.getStatus().equals(MediaPlayer.Status.PLAYING))
                    {
                        double currSec = mediaPlayer.getCurrentTime().toSeconds();
                        String currentSimpleTimeStamp = dash.getSecondsToSimpleString(currSec);
                        Platform.runLater(()->dash.nowDurLabel.setText(currentSimpleTimeStamp));

                        double currentProgress = (currSec/totalCurr)*100;
                        if(!dash.songSeek.isValueChanging())
                        {
                            dash.songSeek.setValue(currentProgress);
                            //dash.refreshSlider(dash.songSeek);
                            currentP = currentProgress;
                        }
                    }
                    Thread.sleep(500);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
    });
    updaterThread.start();
}