下面列出了javafx.scene.control.cell.ComboBoxTableCell#javafx.concurrent.Task 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
* 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();
}
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);
}
/**
* 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;
}
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();
}
/** 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();
}
@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;
}
};
}
@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;
}
};
}
@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;
}
};
}
@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));
}
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();
}
}
@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;
}
}
};
}
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();
}
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;
}
@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;
}
}
};
}
@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;
}
};
}
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);
}
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();
}
@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;
}
};
}
@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);
}
}
/**
* 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);
}
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);
}
@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);
}
}
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
}
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());
}
}
@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);
}
}};
}
@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;
}
}
};
}
@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();
}
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();
}
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);
}
}
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();
}