Example usage for javafx.application Platform isFxApplicationThread

List of usage examples for javafx.application Platform isFxApplicationThread

Introduction

In this page you can find the example usage for javafx.application Platform isFxApplicationThread.

Prototype

public static boolean isFxApplicationThread() 

Source Link

Document

Returns true if the calling thread is the JavaFX Application Thread.

Usage

From source file:com.panemu.tiwulfx.table.TableControl.java

public TableControl(Class<R> recordClass) {
    this.recordClass = recordClass;
    initControls();// w  w  w  .j  a  va 2  s.  c o m

    tblView.getSortOrder().addListener(new ListChangeListener<TableColumn<R, ?>>() {
        @Override
        public void onChanged(ListChangeListener.Change<? extends TableColumn<R, ?>> change) {
            reload();
        }
    });

    btnAdd.disableProperty().bind(mode.isEqualTo(Mode.EDIT));
    btnEdit.disableProperty().bind(mode.isNotEqualTo(Mode.READ));
    btnSave.disableProperty().bind(mode.isEqualTo(Mode.READ));
    btnDelete.disableProperty().bind(new BooleanBinding() {
        {
            super.bind(mode, tblView.getSelectionModel().selectedItemProperty(), lstChangedRow);
        }

        @Override
        protected boolean computeValue() {
            if ((mode.get() == Mode.INSERT && lstChangedRow.size() < 2)
                    || tblView.getSelectionModel().selectedItemProperty().get() == null
                    || mode.get() == Mode.EDIT) {
                return true;
            }
            return false;
        }
    });
    tblView.editableProperty().bind(mode.isNotEqualTo(Mode.READ));
    tblView.getSelectionModel().cellSelectionEnabledProperty().bind(tblView.editableProperty());
    mode.addListener(new ChangeListener<Mode>() {
        @Override
        public void changed(ObservableValue<? extends Mode> ov, Mode t, Mode t1) {
            if (t1 == Mode.READ) {
                directEdit = false;
            }
        }
    });

    tblView.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
            lblRowIndex
                    .setText(TiwulFXUtil.getLiteral("row.param", (page * maxResult.get() + t1.intValue() + 1)));
        }
    });

    tblView.getFocusModel().focusedCellProperty().addListener(new ChangeListener<TablePosition>() {
        @Override
        public void changed(ObservableValue<? extends TablePosition> observable, TablePosition oldValue,
                TablePosition newValue) {
            if (tblView.isEditable() && directEdit && agileEditing.get()) {
                tblView.edit(newValue.getRow(), newValue.getTableColumn());
            }
        }
    });

    tblView.setOnKeyPressed(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.ESCAPE) {
                directEdit = false;
            } else if (event.getCode() == KeyCode.ENTER && mode.get() == Mode.READ) {
                getController().doubleClick(getSelectionModel().getSelectedItem());
            }
        }
    });

    /**
     * Define policy for TAB key press
     */
    tblView.addEventFilter(KeyEvent.KEY_PRESSED, tableKeyListener);
    /**
     * In INSERT mode, only inserted row that is focusable
     */
    tblView.getFocusModel().focusedCellProperty().addListener(tableFocusListener);

    tblView.setOnMouseReleased(tableRightClickListener);

    if (Platform.isFxApplicationThread()) {
        cm = new ContextMenu();
        cm.setAutoHide(true);
        setToolTips();
        /**
         * create custom row factory that can intercept double click on grid row
         */
        tblView.setRowFactory(new Callback<TableView<R>, TableRow<R>>() {
            @Override
            public TableRow<R> call(TableView<R> param) {
                return new TableRowControl(TableControl.this);
            }
        });
    }

    columns.addListener(new ListChangeListener<TableColumn<R, ?>>() {
        @Override
        public void onChanged(ListChangeListener.Change<? extends TableColumn<R, ?>> change) {
            while (change.next()) {
                if (change.wasAdded()) {
                    for (TableColumn<R, ?> column : change.getAddedSubList()) {
                        initColumn(column);
                    }
                }
                lastColumnIndex = getLeafColumns().size() - 1;
            }
        }
    });
    attachWindowVisibilityListener();
}

From source file:io.github.mzmine.modules.plots.msspectrum.MsSpectrumPlotWindowController.java

/**
 * Add a new spectrum to the plot.// w  w w.j  a va2 s .com
 * 
 * @param spectrum
 */
public void addSpectrum(@Nonnull MsSpectrum spectrum, @Nonnull String name) {

    Preconditions.checkNotNull(spectrum);

    if (!Platform.isFxApplicationThread()) {
        throw new IllegalStateException(
                "Not on FX application thread; currentThread = " + Thread.currentThread().getName());
    }

    MsSpectrumDataSet newDataSet = new MsSpectrumDataSet(spectrum, name);
    newDataSet.mzShiftProperty().bind(mzShift);
    datasets.add(newDataSet);

    final int datasetIndex = numberOfDataSets;
    numberOfDataSets++;

    final XYPlot plot = chartNode.getChart().getXYPlot();

    final Color newColor = plotColors[datasetIndex % plotColors.length];
    newDataSet.setColor(newColor);

    configureRenderer(newDataSet, datasetIndex);

    newDataSet.renderingTypeProperty().addListener(e -> {
        Platform.runLater(() -> configureRenderer(newDataSet, datasetIndex));
    });
    newDataSet.colorProperty().addListener(e -> {
        Platform.runLater(() -> configureRenderer(newDataSet, datasetIndex));
    });
    newDataSet.lineThicknessProperty().addListener(e -> {
        Platform.runLater(() -> configureRenderer(newDataSet, datasetIndex));
    });
    newDataSet.showDataPointsProperty().addListener(e -> {
        Platform.runLater(() -> configureRenderer(newDataSet, datasetIndex));
    });

    // Once everything is configured, add the dataset to the plot
    plot.setDataset(datasetIndex, newDataSet);

}

From source file:gov.va.isaac.gui.ConceptNode.java

public void clear() {
    logger.debug("Clear called");
    Runnable r = new Runnable() {
        @Override//from   ww w.  j a v  a 2s. com
        public void run() {
            cb_.setValue(new SimpleDisplayConcept("", 0));
        }
    };

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

From source file:org.martus.client.swingui.PureFxMainWindow.java

public void runInUiThreadAndWait(final Runnable toRun) throws InterruptedException, InvocationTargetException {
    if (Platform.isFxApplicationThread()) {
        toRun.run();/*from w  w  w.j av  a 2  s. c om*/
        return;
    }

    final CountDownLatch doneLatch = new CountDownLatch(1);
    Platform.runLater(() -> {
        try {
            toRun.run();
        } finally {
            doneLatch.countDown();
        }
    });

    doneLatch.await();
}

From source file:de.dkfz.roddy.client.fxuiclient.RoddyUIController.java

private void refillListOfDataSets() {
    //TODO Think about a good update mechanism Maybe a counter which only allowes update if the count fits?
    if (!Platform.isFxApplicationThread()) {
        Platform.runLater(new Runnable() {
            @Override/*from   w w w  . jav  a  2 s .c om*/
            public void run() {
                refillListOfDataSets();
            }
        });
        return;
    }

    List<FXDataSetWrapper> newList;
    List<FXDataSetWrapper> acceptedItems = new LinkedList<>();

    synchronized (currentListOfDataSets) {
        newList = new LinkedList<>(currentListOfDataSets);
    }
    try {
        WildcardFileFilter wff = new WildcardFileFilter(txtDataSetFilter.getText());
        listViewDataSets.getSelectionModel().select(-1);
        listViewDataSets.getItems().clear();
        for (FXDataSetWrapper dsw : newList) {
            if (wff.accept(new File(dsw.getId()))) {
                acceptedItems.add(dsw);
            }
        }
        listViewDataSets.getItems().addAll(acceptedItems);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private boolean connectionCheck() {
    if (lab.getConnection() == null) {
        if (Platform.isFxApplicationThread()) {
            Dialogs.create().title("No ESP Device Selected").message("Choose an ESP device first")
                    .showWarning();//from   ww  w.j  a v a2 s  .c om
        } else {
            JOptionPane.showMessageDialog(this, "Choose an ESP device first", "No ESP Device Selected",
                    JOptionPane.ERROR_MESSAGE);
        }
        return false;
    }

    return true;
}

From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginViewController.java

public static void runLaterIfNotFXApplicationThread(Runnable work) {
    if (Platform.isFxApplicationThread()) {
        work.run();/*  w  w  w .  ja  v  a2  s .  c  o  m*/
    } else {
        Platform.runLater(work);
    }
}

From source file:org.dataconservancy.packaging.gui.presenter.impl.OpenExistingPackagePresenterImpl.java

private void bind() {
    if (loadPackageBackgroundService == null) {
        loadPackageBackgroundService = new BackgroundPackageService();
    }/*from w w w .  java  2  s.  co  m*/

    // Background load service called when continue button fired
    loadPackageBackgroundService.setOnSucceeded(t -> {
        if (Platform.isFxApplicationThread()) {
            view.getProgressPopup().hide();
        }

        OpenedPackage pkg = (OpenedPackage) t.getSource().getValue();

        loadPackageBackgroundService.reset();

        controller.setPackageState(pkg.getPackageState());
        controller.setPackageTree(pkg.getPackageTree());

        if (pkg.getBaseDirectory() == null) {
            // Package state was loaded, go to next page.

            controller.setPackageStateFileChooserInitialChoice(selectedFile);
            controller.goToNextPage();
        } else {
            // Package was loaded, save state and go to next page.
            super.onContinuePressed();
        }
    });

    loadPackageBackgroundService.setOnFailed(workerStateEvent -> {
        if (Platform.isFxApplicationThread()) {
            view.getProgressPopup().hide();
        }

        if (workerStateEvent.getSource().getMessage() == null
                || workerStateEvent.getSource().getMessage().isEmpty()) {
            Throwable e = workerStateEvent.getSource().getException();
            showError(TextFactory.format(ErrorKey.PACKAGE_STATE_LOAD_ERROR, e.getMessage()));
            log.error(e.getMessage());
        } else {
            showError(workerStateEvent.getSource().getMessage());
        }

        loadPackageBackgroundService.reset();
    });

    loadPackageBackgroundService.setOnCancelled(workerStateEvent -> {
        if (Platform.isFxApplicationThread()) {
            view.getProgressPopup().hide();
        }

        showError(workerStateEvent.getSource().getMessage());

        loadPackageBackgroundService.reset();
    });

    // User changes staging directory
    view.getChoosePackageStagingDirectoryButton().setOnAction(event -> {
        File file = controller.showOpenDirectoryDialog(directoryChooser);

        if (file == null) {
            return;
        }

        stagingDir = file;
        view.getChoosePackageStagingDirectoryTextField().setText(stagingDir.getPath());
    });

    // User selects an serialized package or a package state
    view.getChoosePackageFileButton().setOnAction(event -> {
        //Disables file extension filtering on mac since it doesn't seem to reliably work
        if (!SystemUtils.IS_OS_MAC) {
            fileChooser.getExtensionFilters().clear();
            fileChooser.getExtensionFilters()
                    .add(new FileChooser.ExtensionFilter("Package File", "*.zip", "*.ZIP", "*.tar", "*.TAR",
                            "*.gz", "*.GZ", "*.gzip", "*.GZIP", controller.getPackageStateFileExtension()));
            fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("All files (*.*)", "*.*"));
        }

        File file = controller.showOpenFileDialog(fileChooser);

        if (file == null) {
            return;
        }

        clear();
        view.getChoosePackageFileTextField().setText(file.getName());
        view.getContinueButton().setDisable(false);

        selectedFile = file;

        // Check if package or state file
        String state_ext = controller.getPackageStateFileExtension().substring(1);

        if (selectedFile.getName().endsWith(state_ext)) {
            selectedFileType = FILE_TYPE.STATE_FILE;
        } else {
            selectedFileType = FILE_TYPE.PACKAGE;
        }
    });

    // User selects an exploded package
    view.getChooseExplodedPackageDirectoryButton().setOnAction(event -> {
        File file = controller.showOpenDirectoryDialog(directoryChooser);

        if (file == null) {
            return;
        }

        clear();
        view.getChooseExplodedPackageDirectoryTextField().setText(file.getName());
        view.getContinueButton().setDisable(false);

        selectedFile = file;
        selectedFileType = FILE_TYPE.EXPLODED_PACKAGE;
    });
}

From source file:org.dataconservancy.packaging.gui.presenter.impl.OpenExistingPackagePresenterImpl.java

@Override
public void onContinuePressed() {
    loadPackageBackgroundService.execute(selectedFile, selectedFileType);

    if (Platform.isFxApplicationThread()) {
        view.getProgressPopup().show();//from w w  w .  j a v  a2 s . com
    }
}

From source file:org.dataconservancy.packaging.gui.presenter.impl.PackageGenerationPresenterImpl.java

private void bind() {
    if (backgroundService == null) {
        backgroundService = new BackgroundPackageService();
    }/*  w w w  .  j a v  a 2 s.  c  o  m*/

    backgroundService.setOnSucceeded(t -> {
        if (Platform.isFxApplicationThread()) {
            view.getProgressPopup().hide();
            view.showSuccessPopup();
            view.scrollToTop();
        }
        backgroundService.reset();
    });

    backgroundService.setOnFailed(workerStateEvent -> {

        view.getProgressPopup().hide();
        if (workerStateEvent.getSource().getMessage() == null
                || workerStateEvent.getSource().getMessage().isEmpty()) {
            Throwable e = workerStateEvent.getSource().getException();
            view.getStatusLabel()
                    .setText(errors.get(ErrorKey.PACKAGE_GENERATION_CREATION_ERROR) + " " + e.getMessage());
        } else {
            view.getStatusLabel().setText(workerStateEvent.getSource().getMessage());
        }

        view.getStatusLabel().setTextFill(Color.RED);
        view.getStatusLabel().setVisible(true);
        view.scrollToTop();
        backgroundService.reset();
    });

    backgroundService.setOnCancelled(workerStateEvent -> {
        if (Platform.isFxApplicationThread()) {
            view.getProgressPopup().hide();
        }
        view.getStatusLabel().setText(workerStateEvent.getSource().getMessage());
        view.getStatusLabel().setTextFill(Color.RED);
        view.getStatusLabel().setVisible(true);
        view.scrollToTop();
        backgroundService.reset();
    });

    //Handles the user pressing the button to set an output directory where the package will be saved.
    view.getSelectOutputDirectoryButton().setOnAction(arg0 -> {
        File file = controller.showOpenDirectoryDialog(view.getOutputDirectoryChooser());
        if (file != null) {
            controller.setOutputDirectory(file);
            view.getOutputDirectoryChooser().setInitialDirectory(controller.getOutputDirectory());
            //Set the package location parameter based on the new output directory.
            generationParams.addParam(GeneralParameterNames.PACKAGE_LOCATION,
                    controller.getOutputDirectory().getAbsolutePath());

            setOutputDirectory(true);
        }
    });

    //Handles the user changing the package name
    view.getPackageNameField().textProperty().addListener((observableValue, oldVal, newVal) -> {
        setOutputDirectory(true);
    });

    //Handles the user pressing the no thanks link on the create another package popup. This will take the user
    //back to the home screen. 
    view.getNoThanksLink().setOnAction(arg0 -> {
        if (view.getSuccessPopup() != null && view.getSuccessPopup().isShowing()) {
            view.getSuccessPopup().hide();
        }
        controller.showHome(true);
    });

    //Handles the user pressing the create another package button on the create another package popup. This will 
    //dismiss the popup and keep the user on the screen.
    view.getCreateNewPackageButton().setOnAction(arg0 -> {
        if (view.getSuccessPopup() != null && view.getSuccessPopup().isShowing()) {
            view.getSuccessPopup().hide();
        }
        //this will get reset later - need to make sure this is empty now
        generationParams.removeParam(BoremParameterNames.PKG_ORE_REM);
    });

    // This listener is for choosing cancel when overwriting a package file, just closes the popup
    view.getCancelFileOverwriteButton().setOnAction(arg0 -> view.getFileOverwriteWarningPopup().hide());

    // This listener is for choosing to overwrite a package file; closes the window and proceeds
    view.getOkFileOverwriteButton().setOnAction(actionEvent -> {
        view.getFileOverwriteWarningPopup().hide();
        view.getStatusLabel().setVisible(false);
        view.getProgressPopup().show();
        backgroundService.setOverwriteFile(true);
        backgroundService.execute();
    });

    //This listener changes what is shown in the output directory box when the archiving format is changed.
    view.getArchiveToggleGroup().selectedToggleProperty().addListener((ov, toggle, archiveToggle) -> {
        if (archiveToggle != null) {
            setOutputDirectory(true);

            //Set the parameter for the archive format.
            String archiveExtension = (String) archiveToggle.getUserData();
            generationParams.removeParam(GeneralParameterNames.ARCHIVING_FORMAT);

            if (!archiveExtension.isEmpty()) {
                generationParams.addParam(GeneralParameterNames.ARCHIVING_FORMAT, archiveExtension);
            }

            //when we select zip or exploded as our archiving format, we must select 'none' as our compression
            if (archiveExtension.equals("zip") || archiveExtension.equals("exploded")) {
                Toggle noCompressionToggle = getNoCompressionToggle();
                if (noCompressionToggle != null
                        && noCompressionToggle != view.getCompressionToggleGroup().getSelectedToggle()) {
                    view.getCompressionToggleGroup().selectToggle(noCompressionToggle);
                }
            }
        }
    });

    //This listener changes what is shown in the output directory box when the compression format is changed.
    view.getCompressionToggleGroup().selectedToggleProperty().addListener((ov, toggle, compressionToggle) -> {
        if (compressionToggle != null) {
            setOutputDirectory(true);

            //Set the parameter for compression format.
            String compressionExtension = (String) compressionToggle.getUserData();
            generationParams.removeParam(GeneralParameterNames.COMPRESSION_FORMAT);

            if (!compressionExtension.isEmpty()) {
                generationParams.addParam(GeneralParameterNames.COMPRESSION_FORMAT, compressionExtension);
            }
        }
    });

    view.getMd5CheckBox().selectedProperty().addListener((ov, oldValue, newValue) -> {
        List<String> params = generationParams.getParam(BagItParameterNames.CHECKSUM_ALGORITHMS);

        if (newValue) {
            if (params != null && !params.isEmpty() && !params.contains("md5")) {
                params.add("md5");
            }
        } else {
            if (params != null && !params.isEmpty()) {
                params.remove("md5");
            }
        }
    });

    view.getSHA1CheckBox().selectedProperty().addListener((ov, oldValue, newValue) -> {
        List<String> params = generationParams.getParam(BagItParameterNames.CHECKSUM_ALGORITHMS);

        if (newValue) {
            if (params != null && !params.isEmpty() && !params.contains("sha1")) {
                params.add("sha1");
            }
        } else {
            if (params != null && !params.isEmpty()) {
                params.remove("sha1");
            }
        }
    });

    if (Platform.isFxApplicationThread()) {
        ((ProgressDialogPopup) view.getProgressPopup())
                .setCancelEventHandler(event -> backgroundService.cancel());
    }

    /*Handles when the continue button is pressed in the footer. 
    * In this case it creates package params based on the options selected, it then tries to generate a package and save it to the output directory.
    * If successful a popup is shown asking the user if they want to create another package, otherwise an error message is displayed informing the user what went wrong
    * and error is logged.
    */
    view.getContinueButton().setOnAction(arg0 -> {
        view.getStatusLabel().setVisible(false);
        if (Platform.isFxApplicationThread()) {
            view.getProgressPopup().show();
        }
        backgroundService.setOverwriteFile(false);
        backgroundService.execute();
    });
}