Java Code Examples for javafx.application.Platform#isFxApplicationThread()

The following examples show how to use javafx.application.Platform#isFxApplicationThread() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileDeleteHandler.java    From PeerWasp with MIT License 6 votes vote down vote up
private void showError(final String message) {
	Runnable dialog = new Runnable() {
		@Override
		public void run() {
			Alert dlg = DialogUtils.createAlert(AlertType.ERROR);
			dlg.setTitle("Error - Delete.");
			dlg.setHeaderText("Could not delete file(s).");
			dlg.setContentText(message);
			dlg.showAndWait();
		}
	};

	if (Platform.isFxApplicationThread()) {
		dialog.run();
	} else {
		Platform.runLater(dialog);
	}
}
 
Example 2
Source File: ItemSelectionPane.java    From ShootOFF with GNU General Public License v3.0 6 votes vote down vote up
public void removeButton(T ref) {
	if (!items.containsKey(ref)) {
		logger.error("removeButton on non-existing ref - {}", ref);
		return;
	}

	final Node item = items.remove(ref);

	if (Platform.isFxApplicationThread()) {
		subContainer.getChildren().remove(item);
	} else {
		Platform.runLater(() -> subContainer.getChildren().remove(item));
	}

	if (toggleable && ref == defaultSelection) {
		defaultSelection = null;
	}

	if (toggleable && ref == currentSelection && defaultSelection != null) {
		currentSelection = defaultSelection;
		itemListener.onItemClicked(currentSelection);
		toggleGroup.selectToggle((Toggle) items.get(currentSelection));
	}
}
 
Example 3
Source File: CanvasManager.java    From ShootOFF with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Target addTarget(Target newTarget) {
	final Runnable addTargetAction = () -> canvasGroup.getChildren().add(((TargetView) newTarget).getTargetGroup());

	if (Platform.isFxApplicationThread()) {
		addTargetAction.run();
	} else {
		Platform.runLater(addTargetAction);
	}

	targets.add(newTarget);

	// If this is a mirrored canvas, only alert exercises of target updates
	// from the arena window, not the tab. There is no arena tab if we are in
	// headless mode, thus there is also no MirroredCanvasManager. Always
	// perform target update when the canvas isn't mirrored for that reason.
	if (!(this instanceof MirroredCanvasManager)
			|| ((this instanceof MirroredCanvasManager) && arenaPane.isPresent())) {
		final Optional<TrainingExercise> enabledExercise = config.getExercise();
		if (enabledExercise.isPresent())
			enabledExercise.get().targetUpdate(newTarget, TrainingExercise.TargetChange.ADDED);
	}

	return newTarget;
}
 
Example 4
Source File: CanvasManager.java    From ShootOFF with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void clearShots() {
	final Runnable clearShotsAction = () -> {
		for (final DisplayShot shot : shots) {
			canvasGroup.getChildren().remove(shot.getMarker());
		}

		shots.clear();
		try {
			if (shotEntries != null) shotEntries.clear();
		} catch (final NullPointerException npe) {
			logger.error("JDK 8094135 exception", npe);
			jdk8094135Warning();
		}
		if (arenaPane.isPresent() && !(this instanceof MirroredCanvasManager)) arenaPane.get().getCanvasManager().clearShots();
	};

	if (Platform.isFxApplicationThread()) {
		clearShotsAction.run();
	} else {
		Platform.runLater(clearShotsAction);
	}
}
 
Example 5
Source File: JFXUtilities.java    From JFoenix with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to run a specified Runnable in the FX Application thread,
 * it waits for the task to finish before returning to the main thread.
 *
 * @param doRun This is the sepcifed task to be excuted by the FX Application thread
 * @return Nothing
 */
public static void runInFXAndWait(Runnable doRun) {
    if (Platform.isFxApplicationThread()) {
        doRun.run();
        return;
    }
    final CountDownLatch doneLatch = new CountDownLatch(1);
    Platform.runLater(() -> {
        try {
            doRun.run();
        } finally {
            doneLatch.countDown();
        }
    });
    try {
        doneLatch.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
 
Example 6
Source File: Chart.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
/**
 * Notifies listeners that the data has been invalidated. If the data is added to the chart, it triggers repaint.
 *
 * @return itself (fluent design)
 */
public Chart fireInvalidated() {
    synchronized (autoNotification) {
        if (!isAutoNotification() || listeners.isEmpty()) {
            return this;
        }
    }

    if (Platform.isFxApplicationThread()) {
        executeFireInvalidated();
    } else {
        Platform.runLater(this::executeFireInvalidated);
    }

    return this;
}
 
Example 7
Source File: MainController.java    From Noexes with GNU General Public License v3.0 6 votes vote down vote up
public void runAndWait(Runnable r) {
    if (r == null) {
        return;
    }
    if (Platform.isFxApplicationThread()) {
        r.run();
        return;
    }
    Semaphore s = new Semaphore(0);
    Platform.runLater(() -> {
        r.run();
        s.release();
    });
    try {
        s.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: FXNonApplicationThreadRule.java    From gef with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * If the current thread is the JavaFX application thread, busy waiting is
 * performed, i.e. {@link Thread#sleep(long)} is called in-between checking of a
 * {@link CountDownLatch}. Otherwise,
 * {@link CountDownLatch#await(long, TimeUnit)} is used to wait. In either case,
 * an exception is thrown if the timeout of {@link #TIMEOUT_MILLIS} is exceeded.
 *
 * @param latch
 *            The {@link CountDownLatch} that is waited for.
 */
protected void wait(CountDownLatch latch) {
	try {
		if (Platform.isFxApplicationThread()) {
			// busy waiting
			long startMillis = System.currentTimeMillis();
			while (latch.getCount() > 0) {
				Thread.sleep(100);
				if ((System.currentTimeMillis() - startMillis) > TIMEOUT_MILLIS) {
					throw new IllegalStateException("TIMEOUT");
				}
			}
		} else {
			// sleepy waiting
			latch.await(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
		}
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
 
Example 9
Source File: PreviewTab.java    From AsciidocFX with Apache License 2.0 5 votes vote down vote up
public void setChild(Node node) {

        if (super.getContent() == node)
            return;

        if (!Platform.isFxApplicationThread()) {
            Platform.runLater(() -> {
                setChild(node);
            });
            return;
        }

        super.setContent(node);
    }
 
Example 10
Source File: JavaFXMessageHandler.java    From standalone-app with Apache License 2.0 5 votes vote down vote up
public void handleException(Message.FormattedMessage message, Throwable e) {
    e.printStackTrace();
    if (!Platform.isFxApplicationThread()) {
        Platform.runLater(() -> {
            new ExceptionPopupView(stage, message.getText(), e).show();
        });
    } else {
        new ExceptionPopupView(stage, message.getText(), e).show();
    }
}
 
Example 11
Source File: GuiUtils.java    From thunder with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void informationalAlert (String message, String details, Object... args) {
    String formattedDetails = String.format(details, args);
    Runnable r = () -> runAlert((stage, controller) -> controller.informational(stage, message, formattedDetails));
    if (Platform.isFxApplicationThread()) {
        r.run();
    } else {
        Platform.runLater(r);
    }
}
 
Example 12
Source File: Display.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Override
public void playbackFinished(final PlaybackResult result, boolean shutdown) {
    this.autShutdown = shutdown;
    displayView.endTest(result);
    if (ddTestRunner != null && ddTestRunner.hasNext() && !playbackStopped) {
        ddTestRunner.next();
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (result.failureCount() == 0) {
                    shouldClose = !reuseFixture;
                    displayView.trackProgress();
                    ignoreReuse = false;
                } else {
                    ignoreReuse = true;
                    shouldClose = false;
                }
                stopApplicationIfNecessary();
                runTest(debugging);
            }
        });
        return;
    }
    displayView.stopInserting();
    if (Platform.isFxApplicationThread()) {
        showResult(result);
    } else {
        Platform.runLater(() -> showResult(result));
    }
    displayView.endTestRun();
    ddTestRunner = null;
}
 
Example 13
Source File: TimingDAO.java    From pikatimer with GNU General Public License v3.0 5 votes vote down vote up
void blockingClearCookedTimes(TimingLocationInput tli) {
    if (Platform.isFxApplicationThread()) System.out.println("clockingClearCookedTimes called on FxApplicationThread!!!");
    List<CookedTimeData> toRemoveList = new ArrayList<>();
    cookedTimeList.stream().forEach(c -> { 
        if (Objects.equals(c.getTimingLocationInputId(), tli.getID()) ) {
            toRemoveList.add(c);
            if (cookedTimeBibMap.get(c.getBib()) != null) cookedTimeBibMap.get(c.getBib()).remove(c);
        }
     });
    Platform.runLater(() -> {
        cookedTimeList.removeAll(toRemoveList); 
    });
    toRemoveList.stream().forEach(c -> {
        if (!cookedTimeBibMap.containsKey(c.getBib())) cookedTimeBibMap.get(c.getBib()).remove(c);
        resultsQueue.add(c.getBib());
    });

    Session s=HibernateUtil.getSessionFactory().getCurrentSession();
    s.beginTransaction();
    System.out.println("Deleting all cooked times for " + tli.getLocationName());

    try {  
        s.createQuery("delete from CookedTimeData where timingLocationInputId = :tli_id").setParameter("tli_id", tli.getID()).executeUpdate();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    } 
    s.getTransaction().commit(); 
    System.out.println("Done deleting all cooked times for " + tli.getLocationName());


}
 
Example 14
Source File: RectangleRegion.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setFill(Color fill) {
	if (Platform.isFxApplicationThread()) {
		super.setFill(fill);
	} else {
		Platform.runLater(() -> super.setFill(fill));
	}
}
 
Example 15
Source File: SetSampleShapeCommand.java    From megan-ce with GNU General Public License v3.0 5 votes vote down vote up
/**
 * action to be performed
 *
 * @param ev
 */
public void actionPerformed(ActionEvent ev) {
    final SamplesViewer viewer = (SamplesViewer) getViewer();

    final Collection<String> selected = viewer.getSamplesTableView().getSelectedSamples();

    if (selected.size() > 0) {
        String sample = selected.iterator().next();
        String shapeLabel = viewer.getSampleAttributeTable().getSampleShape(sample);
        NodeShape nodeShape = NodeShape.valueOfIgnoreCase(shapeLabel);
        if (nodeShape == null)
            nodeShape = NodeShape.Oval;
        final NodeShape nodeShape1 = nodeShape;

        Runnable runnable = () -> {
            final ChoiceDialog<NodeShape> dialog = new ChoiceDialog<>(nodeShape1, NodeShape.values());
            dialog.setTitle("MEGAN choice");
            dialog.setHeaderText("Choose shape to represent sample(s)");
            dialog.setContentText("Shape:");

            final Optional<NodeShape> result = dialog.showAndWait();
            result.ifPresent(shape -> execute("set nodeShape=" + shape + " sample='" + Basic.toString(selected, "' '") + "';"));
        };
        if (Platform.isFxApplicationThread())
            runnable.run();
        else
            Platform.runLater(runnable);
    }
}
 
Example 16
Source File: HeadlessController.java    From ShootOFF with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setProjectorExercise(TrainingExercise exercise) {
	try {
		config.setExercise(null);

		final Constructor<?> ctor = exercise.getClass().getConstructor(List.class);
		final TrainingExercise newExercise = (TrainingExercise) ctor.newInstance(arenaCanvasManager.getTargets());

		final Optional<Plugin> plugin = pluginEngine.getPlugin(newExercise);
		if (plugin.isPresent()) {
			config.setPlugin(plugin.get());
		} else {
			config.setPlugin(null);
		}

		config.setExercise(newExercise);

		final Runnable initExercise = () -> {
			((ProjectorTrainingExerciseBase) newExercise).init(camerasSupervisor, this, arenaPane);
			newExercise.init();
		};

		if (Platform.isFxApplicationThread()) {
			initExercise.run();
		} else {
			Platform.runLater(initExercise);
		}

	} catch (final ReflectiveOperationException e) {
		final ExerciseMetadata metadata = exercise.getInfo();
		logger.error("Failed to start projector exercise " + metadata.getName() + " " + metadata.getVersion(), e);
	}
}
 
Example 17
Source File: MarkerOptions.java    From FXMaps with GNU Affero General Public License v3.0 5 votes vote down vote up
public void createUnderlying() {
    if(Platform.isFxApplicationThread()) {
        options = new com.lynden.gmapsfx.javascript.object.MarkerOptions()
            .title(title)
            .position(position.toLatLong())
            .visible(visible);
        if(animation != null) {
            options.animation(animation.convert());
        }
        if(iconPath != null) {
            options.icon(iconPath);
        }
    }
}
 
Example 18
Source File: FXBrowserWindowSE.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void show() {
    if (!Platform.isFxApplicationThread()) {
        Platform.runLater(new Runnable() {
            public void run() {
                show();
            }
        });
        return;
    }
    stage.show();
}
 
Example 19
Source File: JavaFxHtmlToolkit.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isApplicationThread() {
    return Platform.isFxApplicationThread();
}
 
Example 20
Source File: SamplesTableView.java    From megan-ce with GNU General Public License v3.0 4 votes vote down vote up
private static void ensureFXThread(Runnable runnable) {
    if (Platform.isFxApplicationThread())
        runnable.run();
    else
        Platform.runLater(runnable);
}