Example usage for javafx.scene.input Clipboard getSystemClipboard

List of usage examples for javafx.scene.input Clipboard getSystemClipboard

Introduction

In this page you can find the example usage for javafx.scene.input Clipboard getSystemClipboard.

Prototype

public static Clipboard getSystemClipboard() 

Source Link

Document

Gets the current system clipboard, through which data can be stored and retrieved.

Usage

From source file:org.sandsoft.acefx.AceEditor.java

/**
 * Paste text from clipboard after the cursor.
 */
public void doPaste() {
    getEditor().insert(Clipboard.getSystemClipboard().getString());
}

From source file:org.sandsoft.acefx.AceEditor.java

/**
 * Copies the selected text to clipboard.
 *
 * @return True if performed successfully.
 *//*  w w w  .j  a  va  2 s . co m*/
public boolean doCopy() {
    String copy = mEditor.getCopyText();
    if (copy != null && !copy.isEmpty()) {
        ClipboardContent content = new ClipboardContent();
        content.putString(copy);
        Clipboard.getSystemClipboard().setContent(content);
        return true;
    }
    return false;
}

From source file:com.chart.SwingChart.java

/**
 * Copy to clipboard/*w  ww . ja va2 s.  c  o  m*/
 * @param node JavaFX Node to copy
 */
public final void copyClipboard(final Node node) {

    WritableImage captura = node.snapshot(new SnapshotParameters(), null);

    ImageView iv = new ImageView(captura);

    Clipboard clipboard = Clipboard.getSystemClipboard();
    ClipboardContent content = new ClipboardContent();
    content.put(DataFormat.IMAGE, captura);
    clipboard.setContent(content);

}

From source file:qupath.lib.gui.tma.TMASummaryViewer.java

private void initialize() {

    model = new TMATableModel();

    groupByIDProperty.addListener((v, o, n) -> refreshTableData());

    MenuBar menuBar = new MenuBar();
    Menu menuFile = new Menu("File");
    MenuItem miOpen = new MenuItem("Open...");
    miOpen.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN));
    miOpen.setOnAction(e -> {/* ww  w. j a  v a 2 s.  c  om*/
        File file = QuPathGUI.getDialogHelper(stage).promptForFile(null, null, "TMA data files",
                new String[] { "qptma" });
        if (file == null)
            return;
        setInputFile(file);
    });

    MenuItem miSave = new MenuItem("Save As...");
    miSave.setAccelerator(
            new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    miSave.setOnAction(
            e -> SummaryMeasurementTableCommand.saveTableModel(model, null, Collections.emptyList()));

    MenuItem miImportFromImage = new MenuItem("Import from current image...");
    miImportFromImage.setAccelerator(
            new KeyCodeCombination(KeyCode.I, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    miImportFromImage.setOnAction(e -> setTMAEntriesFromOpenImage());

    MenuItem miImportFromProject = new MenuItem("Import from current project... (experimental)");
    miImportFromProject.setAccelerator(
            new KeyCodeCombination(KeyCode.P, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    miImportFromProject.setOnAction(e -> setTMAEntriesFromOpenProject());

    MenuItem miImportClipboard = new MenuItem("Import from clipboard...");
    miImportClipboard.setOnAction(e -> {
        String text = Clipboard.getSystemClipboard().getString();
        if (text == null) {
            DisplayHelpers.showErrorMessage("Import scores", "Clipboard is empty!");
            return;
        }
        int n = importScores(text);
        if (n > 0) {
            setTMAEntries(new ArrayList<>(entriesBase));
        }
        DisplayHelpers.showMessageDialog("Import scores", "Number of scores imported: " + n);
    });

    Menu menuEdit = new Menu("Edit");
    MenuItem miCopy = new MenuItem("Copy table to clipboard");
    miCopy.setOnAction(e -> {
        SummaryMeasurementTableCommand.copyTableContentsToClipboard(model, Collections.emptyList());
    });

    combinedPredicate.addListener((v, o, n) -> {
        // We want any other changes triggered by this to have happened, 
        // so that the data has already been updated
        Platform.runLater(() -> handleTableContentChange());
    });

    // Reset the scores for missing cores - this ensures they will be NaN and not influence subsequent results
    MenuItem miResetMissingScores = new MenuItem("Reset scores for missing cores");
    miResetMissingScores.setOnAction(e -> {
        int changes = 0;
        for (TMAEntry entry : entriesBase) {
            if (!entry.isMissing())
                continue;
            boolean changed = false;
            for (String m : entry.getMeasurementNames().toArray(new String[0])) {
                if (!TMASummaryEntry.isSurvivalColumn(m) && !Double.isNaN(entry.getMeasurementAsDouble(m))) {
                    entry.putMeasurement(m, null);
                    changed = true;
                }
            }
            if (changed)
                changes++;
        }
        if (changes == 0) {
            logger.info("No changes made when resetting scores for missing cores!");
            return;
        }
        logger.info("{} change(s) made when resetting scores for missing cores!", changes);
        table.refresh();
        updateSurvivalCurves();
        if (scatterPane != null)
            scatterPane.updateChart();
        if (histogramDisplay != null)
            histogramDisplay.refreshHistogram();
    });
    menuEdit.getItems().add(miResetMissingScores);

    QuPathGUI.addMenuItems(menuFile, miOpen, miSave, null, miImportClipboard, null, miImportFromImage,
            miImportFromProject);
    menuBar.getMenus().add(menuFile);
    menuEdit.getItems().add(miCopy);
    menuBar.getMenus().add(menuEdit);

    menuFile.setOnShowing(e -> {
        boolean imageDataAvailable = QuPathGUI.getInstance() != null
                && QuPathGUI.getInstance().getImageData() != null
                && QuPathGUI.getInstance().getImageData().getHierarchy().getTMAGrid() != null;
        miImportFromImage.setDisable(!imageDataAvailable);
        boolean projectAvailable = QuPathGUI.getInstance() != null
                && QuPathGUI.getInstance().getProject() != null
                && !QuPathGUI.getInstance().getProject().getImageList().isEmpty();
        miImportFromProject.setDisable(!projectAvailable);
    });

    // Double-clicking previously used for comments... but conflicts with tree table expansion
    //      table.setOnMouseClicked(e -> {
    //         if (!e.isPopupTrigger() && e.getClickCount() > 1)
    //            promptForComment();
    //      });

    table.setPlaceholder(new Text("Drag TMA data folder onto window, or choose File -> Open"));
    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    BorderPane pane = new BorderPane();
    pane.setTop(menuBar);
    menuBar.setUseSystemMenuBar(true);

    // Create options
    ToolBar toolbar = new ToolBar();
    Label labelMeasurementMethod = new Label("Combination method");
    labelMeasurementMethod.setLabelFor(comboMeasurementMethod);
    labelMeasurementMethod
            .setTooltip(new Tooltip("Method whereby measurements for multiple cores with the same "
                    + TMACoreObject.KEY_UNIQUE_ID + " will be combined"));

    CheckBox cbHidePane = new CheckBox("Hide pane");
    cbHidePane.setSelected(hidePaneProperty.get());
    cbHidePane.selectedProperty().bindBidirectional(hidePaneProperty);

    CheckBox cbGroupByID = new CheckBox("Group by ID");
    entriesBase.addListener((Change<? extends TMAEntry> event) -> {
        if (!event.getList().stream().anyMatch(e -> e.getMetadataValue(TMACoreObject.KEY_UNIQUE_ID) != null)) {
            cbGroupByID.setSelected(false);
            cbGroupByID.setDisable(true);
        } else {
            cbGroupByID.setDisable(false);
        }
    });
    cbGroupByID.setSelected(groupByIDProperty.get());
    cbGroupByID.selectedProperty().bindBidirectional(groupByIDProperty);

    CheckBox cbUseSelected = new CheckBox("Use selection only");
    cbUseSelected.selectedProperty().bindBidirectional(useSelectedProperty);

    CheckBox cbSkipMissing = new CheckBox("Hide missing cores");
    cbSkipMissing.selectedProperty().bindBidirectional(skipMissingCoresProperty);
    skipMissingCoresProperty.addListener((v, o, n) -> {
        table.refresh();
        updateSurvivalCurves();
        if (histogramDisplay != null)
            histogramDisplay.refreshHistogram();
        updateSurvivalCurves();
        if (scatterPane != null)
            scatterPane.updateChart();
    });

    toolbar.getItems().addAll(labelMeasurementMethod, comboMeasurementMethod,
            new Separator(Orientation.VERTICAL), cbHidePane, new Separator(Orientation.VERTICAL), cbGroupByID,
            new Separator(Orientation.VERTICAL), cbUseSelected, new Separator(Orientation.VERTICAL),
            cbSkipMissing);
    comboMeasurementMethod.getItems().addAll(MeasurementCombinationMethod.values());
    comboMeasurementMethod.getSelectionModel().select(MeasurementCombinationMethod.MEDIAN);
    selectedMeasurementCombinationProperty.addListener((v, o, n) -> table.refresh());

    ContextMenu popup = new ContextMenu();
    MenuItem miSetMissing = new MenuItem("Set missing");
    miSetMissing.setOnAction(e -> setSelectedMissingStatus(true));

    MenuItem miSetAvailable = new MenuItem("Set available");
    miSetAvailable.setOnAction(e -> setSelectedMissingStatus(false));

    MenuItem miExpand = new MenuItem("Expand all");
    miExpand.setOnAction(e -> {
        if (table.getRoot() == null)
            return;
        for (TreeItem<?> item : table.getRoot().getChildren()) {
            item.setExpanded(true);
        }
    });
    MenuItem miCollapse = new MenuItem("Collapse all");
    miCollapse.setOnAction(e -> {
        if (table.getRoot() == null)
            return;
        for (TreeItem<?> item : table.getRoot().getChildren()) {
            item.setExpanded(false);
        }
    });
    popup.getItems().addAll(miSetMissing, miSetAvailable, new SeparatorMenuItem(), miExpand, miCollapse);
    table.setContextMenu(popup);

    table.setRowFactory(e -> {
        TreeTableRow<TMAEntry> row = new TreeTableRow<>();

        //         // Make rows invisible if they don't pass the predicate
        //         row.visibleProperty().bind(Bindings.createBooleanBinding(() -> {
        //               TMAEntry entry = row.getItem();
        //               if (entry == null || (entry.isMissing() && skipMissingCoresProperty.get()))
        //                     return false;
        //               return entries.getPredicate() == null || entries.getPredicate().test(entry);
        //               },
        //               skipMissingCoresProperty,
        //               entries.predicateProperty()));

        // Style rows according to what they contain
        row.styleProperty().bind(Bindings.createStringBinding(() -> {
            if (row.isSelected())
                return "";
            TMAEntry entry = row.getItem();
            if (entry == null || entry instanceof TMASummaryEntry)
                return "";
            else if (entry.isMissing())
                return "-fx-background-color:rgb(225,225,232)";
            else
                return "-fx-background-color:rgb(240,240,245)";
        }, row.itemProperty(), row.selectedProperty()));
        //         row.itemProperty().addListener((v, o, n) -> {
        //            if (n == null || n instanceof TMASummaryEntry || row.isSelected())
        //               row.setStyle("");
        //            else if (n.isMissing())
        //               row.setStyle("-fx-background-color:rgb(225,225,232)");            
        //            else
        //               row.setStyle("-fx-background-color:rgb(240,240,245)");            
        //         });
        return row;
    });

    BorderPane paneTable = new BorderPane();
    paneTable.setTop(toolbar);
    paneTable.setCenter(table);

    MasterDetailPane mdTablePane = new MasterDetailPane(Side.RIGHT, paneTable, createSidePane(), true);

    mdTablePane.showDetailNodeProperty().bind(Bindings.createBooleanBinding(
            () -> !hidePaneProperty.get() && !entriesBase.isEmpty(), hidePaneProperty, entriesBase));
    mdTablePane.setDividerPosition(2.0 / 3.0);

    pane.setCenter(mdTablePane);

    model.getEntries().addListener(new ListChangeListener<TMAEntry>() {
        @Override
        public void onChanged(ListChangeListener.Change<? extends TMAEntry> c) {
            if (histogramDisplay != null)
                histogramDisplay.refreshHistogram();
            updateSurvivalCurves();
            if (scatterPane != null)
                scatterPane.updateChart();
        }
    });

    Label labelPredicate = new Label();
    labelPredicate.setPadding(new Insets(5, 5, 5, 5));
    labelPredicate.setAlignment(Pos.CENTER);
    //      labelPredicate.setStyle("-fx-background-color: rgba(20, 120, 20, 0.15);");
    labelPredicate.setStyle("-fx-background-color: rgba(120, 20, 20, 0.15);");

    labelPredicate.textProperty().addListener((v, o, n) -> {
        if (n.trim().length() > 0)
            pane.setBottom(labelPredicate);
        else
            pane.setBottom(null);
    });
    labelPredicate.setMaxWidth(Double.MAX_VALUE);
    labelPredicate.setMaxHeight(labelPredicate.getPrefHeight());
    labelPredicate.setTextAlignment(TextAlignment.CENTER);
    predicateMeasurements.addListener((v, o, n) -> {
        if (n == null)
            labelPredicate.setText("");
        else if (n instanceof TablePredicate) {
            TablePredicate tp = (TablePredicate) n;
            if (tp.getOriginalCommand().trim().isEmpty())
                labelPredicate.setText("");
            else
                labelPredicate.setText("Predicate: " + tp.getOriginalCommand());
        } else
            labelPredicate.setText("Predicate: " + n.toString());
    });
    //      predicate.set(new TablePredicate("\"Tumor\" > 100"));

    scene = new Scene(pane);

    scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
        KeyCode code = e.getCode();
        if ((code == KeyCode.SPACE || code == KeyCode.ENTER) && entrySelected != null) {
            promptForComment();
            return;
        }
    });

}

From source file:com.joliciel.talismane.terminology.viewer.TerminologyViewerController.java

@FXML
protected void tblTerms_OnKeyPressed(KeyEvent keyEvent) {
    if (keyEvent.isControlDown()) {
        //          LOG.debug("keyEvent.getCharacter(): " + keyEvent.getCharacter());
        //          LOG.debug("keyEvent.getCode().getName(): " + keyEvent.getCode().getName());
        if (keyEvent.getCode().getName().equals("C")) {
            final Clipboard clipboard = Clipboard.getSystemClipboard();
            final ClipboardContent content = new ClipboardContent();
            Term term = tblTerms.getSelectionModel().getSelectedItem();
            content.putString(term.getText());
            clipboard.setContent(content);
        }//ww  w .  j  a v a2 s  .  c  o  m
    } else if (keyEvent.getCode().getName().equalsIgnoreCase("M")) {
        this.markTerm();
    } else if (keyEvent.getCode().getName().equalsIgnoreCase("E")) {
        this.doExpansions();
    } else if (keyEvent.getCode().getName().equalsIgnoreCase("B")) {
        this.doBack();
    } else if (keyEvent.getCode().getName().equalsIgnoreCase("F")) {
        this.doForward();
    }
}

From source file:com.joliciel.talismane.terminology.viewer.TerminologyViewerController.java

@FXML
protected void tblContexts_OnKeyPressed(KeyEvent keyEvent) {
    if (keyEvent.isControlDown()) {
        if (keyEvent.getCode().getName().equals("C")) {
            final Clipboard clipboard = Clipboard.getSystemClipboard();
            final ClipboardContent content = new ClipboardContent();
            Context context = tblContexts.getSelectionModel().getSelectedItem();
            content.putString(context.getTextSegment());
            clipboard.setContent(content);
        }//from   ww  w  . j a v a 2  s  .c  o m
    }
}

From source file:net.rptools.tokentool.controller.TokenTool_Controller.java

@FXML
void editCopyImageMenu_onAction(ActionEvent event) {
    Clipboard clipboard = Clipboard.getSystemClipboard();
    ClipboardContent content = new ClipboardContent();

    // for paste as file, e.g. in Windows Explorer
    try {//w w w.  j a  v a 2 s.co m
        File tempTokenFile = fileSaveUtil.getTempFileName(false, useFileNumberingCheckbox.isSelected(),
                fileNameTextField.getText(), fileNameSuffixTextField);

        writeTokenImage(tempTokenFile);
        content.putFiles(java.util.Collections.singletonList(tempTokenFile));
        tempTokenFile.deleteOnExit();
    } catch (Exception e) {
        log.error(e);
    }

    // for paste as image, e.g. in GIMP
    content.putImage(tokenImageView.getImage());

    // Finally, put contents on clip board
    clipboard.setContent(content);
}

From source file:net.rptools.tokentool.controller.TokenTool_Controller.java

@FXML
void editPasteImageMenu_onAction(ActionEvent event) {
    Clipboard clipboard = Clipboard.getSystemClipboard();
    Image originalImage = portraitImageView.getImage();

    // Strangely, we get an error if we try to paste an image we put in the clipboard ourselves but File works ok?
    // -Dprism.order=sw also fixes it but not sure why...
    // So lets just check for File first...
    if (clipboard.hasFiles()) {
        clipboard.getFiles().forEach(file -> {
            try {
                Image cbImage = new Image(file.toURI().toURL().toExternalForm());

                if (cbImage != null)
                    updatePortrait(cbImage);

                updateFileNameTextField(FilenameUtils.getBaseName(file.toURI().toURL().toExternalForm()));
            } catch (Exception e) {
                log.error("Could not load image " + file);
                e.printStackTrace();//www.j a v a 2s . co m
            }
        });
    } else if (clipboard.hasImage()) {
        try {
            Image cbImage = clipboard.getImage();
            if (cbImage != null)
                updatePortrait(cbImage);
        } catch (IllegalArgumentException e) {
            log.info(e);
            updatePortrait(originalImage);
        }
    } else if (clipboard.hasUrl()) {
        try {
            Image cbImage = new Image(clipboard.getUrl());
            if (cbImage != null)
                updatePortrait(cbImage);

            updateFileNameTextField(FileSaveUtil.searchURL(clipboard.getUrl()));
        } catch (IllegalArgumentException e) {
            log.info(e);
        }
    } else if (clipboard.hasString()) {
        try {
            Image cbImage = new Image(clipboard.getString());
            if (cbImage != null)
                updatePortrait(cbImage);

            updateFileNameTextField(FileSaveUtil.searchURL(clipboard.getString()));
        } catch (IllegalArgumentException e) {
            log.info(e);
        }
    }
}

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

/**
 * Paste text on clipboard. Doesn't work on READ mode.
 *//*from   w  w  w . j  a  va 2 s. c  om*/
public void paste() {
    if (mode.get() == Mode.READ) {
        return;
    }
    final Clipboard clipboard = Clipboard.getSystemClipboard();
    if (clipboard.hasString()) {
        final String text = clipboard.getString();
        if (text != null) {
            List<TablePosition> cells = tblView.getSelectionModel().getSelectedCells();
            if (cells.isEmpty()) {
                return;
            }
            TablePosition cell = cells.get(0);
            List<TableColumn<R, ?>> lstColumn = getLeafColumns();
            TableColumn startColumn = null;
            for (TableColumn clm : lstColumn) {
                if (clm instanceof BaseColumn && clm == cell.getTableColumn()) {
                    startColumn = (BaseColumn) clm;
                    break;
                }
            }
            if (startColumn == null) {
                return;
            }
            int rowIndex = cell.getRow();
            String[] arrString = text.split("\n");
            boolean stopPasting = false;
            for (String line : arrString) {
                if (stopPasting) {
                    break;
                }
                R item = null;
                if (rowIndex < tblView.getItems().size()) {
                    item = tblView.getItems().get(rowIndex);
                } else if (mode.get() == Mode.EDIT) {
                    /**
                     * Will ensure the content display to TEXT_ONLY because
                     * there is no way to update cell editors value (in
                     * agile editing mode)
                     */
                    tblView.getSelectionModel().clearSelection();
                    return;//stop pasting as it already touched last row
                }

                if (!lstChangedRow.contains(item)) {
                    if (mode.get() == Mode.INSERT) {
                        //means that selected row is not new row. Let's create new row
                        createNewRow(rowIndex);
                        item = tblView.getItems().get(rowIndex);
                    } else {
                        lstChangedRow.add(item);
                    }
                }

                showRow(rowIndex);
                /**
                 * Handle multicolumn paste
                 */
                String[] stringCellValues = line.split("\t");
                TableColumn toFillColumn = startColumn;
                tblView.getSelectionModel().select(rowIndex, toFillColumn);
                for (String stringCellValue : stringCellValues) {
                    if (toFillColumn == null) {
                        break;
                    }
                    if (toFillColumn instanceof BaseColumn && toFillColumn.isEditable()
                            && toFillColumn.isVisible()) {
                        try {
                            Object oldValue = toFillColumn.getCellData(item);
                            Object newValue = ((BaseColumn) toFillColumn).convertFromString(stringCellValue);
                            PropertyUtils.setSimpleProperty(item, ((BaseColumn) toFillColumn).getPropertyName(),
                                    newValue);
                            if (mode.get() == Mode.EDIT) {
                                ((BaseColumn) toFillColumn).addRecordChange(item, oldValue, newValue);
                            }
                        } catch (Exception ex) {
                            MessageDialog.Answer answer = MessageDialogBuilder.error(ex)
                                    .message("msg.paste.error", stringCellValue, toFillColumn.getText())
                                    .buttonType(MessageDialog.ButtonType.YES_NO)
                                    .yesOkButtonText("continue.pasting").noButtonText("stop")
                                    .show(getScene().getWindow());
                            if (answer == MessageDialog.Answer.NO) {
                                stopPasting = true;
                                break;
                            }
                        }
                    }
                    tblView.getSelectionModel().selectRightCell();
                    TablePosition nextCell = tblView.getSelectionModel().getSelectedCells().get(0);
                    if (nextCell.getTableColumn() instanceof BaseColumn
                            && nextCell.getTableColumn() != toFillColumn) {
                        toFillColumn = (BaseColumn) nextCell.getTableColumn();
                    } else {
                        toFillColumn = null;
                    }
                }
                rowIndex++;
            }

            refresh();

            /**
             * Will ensure the content display to TEXT_ONLY because there is
             * no way to update cell editors value (in agile editing mode)
             */
            tblView.getSelectionModel().clearSelection();
        }
    }
}

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

public void handleCopySpectra(Event event) {
    StringBuilder sb = new StringBuilder();
    for (MsSpectrumDataSet dataset : datasets) {
        MsSpectrum spectrum = dataset.getSpectrum();
        String spectrumString = TxtExportAlgorithm.spectrumToString(spectrum);
        String splash = SplashCalculationAlgorithm.calculateSplash(spectrum);
        sb.append("# ");
        sb.append(dataset.getName());//from w  w  w. ja v  a 2s  .co m
        sb.append("\n");
        sb.append("# SPLASH ID: ");
        sb.append(splash);
        sb.append("\n");
        sb.append(spectrumString);
        sb.append("\n");
    }
    final Clipboard clipboard = Clipboard.getSystemClipboard();
    final ClipboardContent content = new ClipboardContent();
    content.putString(sb.toString());
    clipboard.setContent(content);
}