Example usage for javafx.scene.control ContextMenu getItems

List of usage examples for javafx.scene.control ContextMenu getItems

Introduction

In this page you can find the example usage for javafx.scene.control ContextMenu getItems.

Prototype

public final ObservableList<MenuItem> getItems() 

Source Link

Document

The menu items on the context menu.

Usage

From source file:account.management.controller.ViewSalaryVoucherController.java

/**
 * Initializes the controller class./*from www  .j a  va 2s  .  com*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    this.voucher_no.setCellValueFactory(new PropertyValueFactory("id"));
    this.date.setCellValueFactory(new PropertyValueFactory("date"));
    this.section.setCellValueFactory(new PropertyValueFactory("section"));
    this.name.setCellValueFactory(new PropertyValueFactory("name"));
    this.basis.setCellValueFactory(new PropertyValueFactory("basis"));
    this.amount.setCellValueFactory(new PropertyValueFactory("total"));

    final ContextMenu contextMenu = new ContextMenu();
    MenuItem item1 = new MenuItem("    View                  ");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            Data.salaryVoucher = table.getSelectionModel().getSelectedItem();

            try {
                Parent root = FXMLLoader
                        .load(getClass().getResource(MetaData.viewPath + "EditSalaryVoucher.fxml"));
                Scene scene = new Scene(root);
                Stage stage = new Stage();
                scene.setRoot(root);
                stage.setResizable(false);
                stage.setTitle("Salary Voucher");
                stage.setScene(scene);
                stage.showAndWait();
                int index = table.getSelectionModel().getSelectedIndex();
                getData();

            } catch (IOException ex) {
                Logger.getLogger(ViewSalaryVoucherController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });
    contextMenu.getItems().addAll(item1);
    this.table.setContextMenu(contextMenu);

}

From source file:net.sourceforge.pmd.util.fxdesigner.XPathPanelController.java

private void autoComplete(int slashPosition, String input, ContextMenu autoCompletePopup) {

    XPathSuggestions xPathSuggestions = new XPathSuggestions(parent.getLanguageVersion().getLanguage());
    List<String> suggestions = xPathSuggestions.getXPathSuggestions(input.trim());

    List<CustomMenuItem> resultToDisplay = new ArrayList<>();
    if (!suggestions.isEmpty()) {

        for (int i = 0; i < suggestions.size() && i < 5; i++) {
            final String searchResult = suggestions.get(i);

            Label entryLabel = new Label();
            entryLabel.setGraphic(highlightXPathSuggestion(suggestions.get(i), input));
            entryLabel.setPrefHeight(5);
            CustomMenuItem item = new CustomMenuItem(entryLabel, true);
            resultToDisplay.add(item);//from   w w w  .j a  v a  2s  .com

            item.setOnAction(e -> {
                xpathExpressionArea.replaceText(slashPosition, slashPosition + input.length(), searchResult);
                autoCompletePopup.hide();
            });
        }
    }
    autoCompletePopup.getItems().setAll(resultToDisplay);

    xpathExpressionArea.getCharacterBoundsOnScreen(slashPosition, slashPosition + input.length()).ifPresent(
            bounds -> autoCompletePopup.show(xpathExpressionArea, bounds.getMinX(), bounds.getMaxY()));
}

From source file:com.heliosdecompiler.helios.gui.view.editors.DisassemblerView.java

@Override
protected Node createView0(OpenedFile file, String path) {
    CodeArea codeArea = new CodeArea();

    if (controller instanceof KrakatauDisassemblerController) {
        ContextMenu contextMenu = new ContextMenu();

        MenuItem save = new MenuItem("Assemble");
        save.setOnAction(e -> {/*from w w w  .j  a v a 2s . co m*/
            save(codeArea).whenComplete((res, err) -> {
                if (err != null) {
                    if (err instanceof KrakatauException) {
                        StringBuilder message = new StringBuilder();
                        message.append("stdout:\r\n").append(((KrakatauException) err).getStdout())
                                .append("\r\n\r\nstderr:\r\n").append(((KrakatauException) err).getStderr());

                        messageHandler.handleLongMessage(Message.ERROR_FAILED_TO_ASSEMBLE_KRAKATAU,
                                message.toString());
                    } else {
                        messageHandler.handleException(Message.ERROR_UNKNOWN_ERROR.format(), err);
                    }
                } else {
                    file.putContent(path, res);
                    messageHandler.handleMessage(Message.GENERIC_ASSEMBLED.format());
                }
            });
        });

        contextMenu.getItems().add(save);
        codeArea.setContextMenu(contextMenu);
    }

    codeArea.setStyle("-fx-font-size: 1em");
    codeArea.getProperties().put("fontSize", 1);

    codeArea.setParagraphGraphicFactory(line -> {
        Node label = LineNumberFactory.get(codeArea, (digits) -> "%1$" + digits + "d").apply(line);
        label.styleProperty().bind(codeArea.styleProperty());
        return label;
    });
    codeArea.replaceText("Disassembling... this may take a while");
    codeArea.getUndoManager().forgetHistory();

    codeArea.richChanges().filter(ch -> !ch.getInserted().equals(ch.getRemoved())) // XXX
            .successionEnds(Duration.ofMillis(500)).supplyTask(() -> computeHighlightingAsync(codeArea))
            .awaitLatest(codeArea.richChanges()).filterMap(t -> {
                if (t.isSuccess()) {
                    return Optional.of(t.get());
                } else {
                    t.getFailure().printStackTrace();
                    return Optional.empty();
                }
            }).subscribe(f -> applyHighlighting(codeArea, f));
    codeArea.getStylesheets().add(getClass().getResource("/java-keywords.css").toExternalForm());

    codeArea.addEventFilter(ScrollEvent.SCROLL, e -> {
        if (e.isShortcutDown()) {
            if (e.getDeltaY() > 0) {
                int size = (int) codeArea.getProperties().get("fontSize") + 1;
                codeArea.setStyle("-fx-font-size: " + size + "em");
                codeArea.getProperties().put("fontSize", size);
            } else {
                int size = (int) codeArea.getProperties().get("fontSize") - 1;
                if (size > 0) {
                    codeArea.setStyle("-fx-font-size: " + size + "em");
                    codeArea.getProperties().put("fontSize", size);
                }
            }
            e.consume();
        }
    });

    controller.disassemble(file, path, (success, text) -> {
        Platform.runLater(() -> {
            codeArea.replaceText(text);
            codeArea.getUndoManager().forgetHistory();
        });
    });

    return new VirtualizedScrollPane<>(codeArea);
}

From source file:com.github.drbookings.ui.controller.MainController.java

private void initTableViewContextMenus() {
    final ContextMenu menu = new ContextMenu();
    final MenuItem mi1 = new MenuItem("Delete");
    final MenuItem mi2 = new MenuItem("Add");
    final MenuItem mi3 = new MenuItem("Modify");
    mi1.setOnAction(event -> {//from w  w w .jav a 2  s. c o  m
        Platform.runLater(() -> deleteSelected());
    });
    mi2.setOnAction(event -> {
        Platform.runLater(() -> addBooking());
    });
    mi3.setOnAction(event -> {
        Platform.runLater(() -> showModifyBookingDialog());
    });
    menu.getItems().addAll(mi2, mi1, mi3);

    tableView.setContextMenu(menu);
    tableView.addEventHandler(MouseEvent.MOUSE_CLICKED, t -> {
        if (t.getButton() == MouseButton.SECONDARY) {
            menu.show(tableView, t.getScreenX(), t.getScreenY());
        }
    });
}

From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java

private void setupTableWithChanges(TableView<Change> tv, Dataset tp) {
    tv.setEditable(true);/*  ww w  .j  a  v  a 2  s .co m*/
    tv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    tv.getColumns().clear();

    TableColumn<Change, ChangeType> colChangeType = new TableColumn<>("Type");
    colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(),
            ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT,
            ChangeType.COMPLEX, ChangeType.ERROR));
    colChangeType.setCellValueFactory(new PropertyValueFactory<>("type"));
    colChangeType.setPrefWidth(100.0);
    colChangeType.setEditable(true);
    tv.getColumns().add(colChangeType);

    TableColumn<Change, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From");
    colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from"));
    colChangeFrom.setPrefWidth(200.0);
    colChangeFrom.setEditable(true);
    tv.getColumns().add(colChangeFrom);

    TableColumn<Change, ObservableSet<Name>> colChangeTo = new TableColumn<>("To");
    colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to"));
    colChangeTo.setPrefWidth(200.0);
    colChangeTo.setEditable(true);
    tv.getColumns().add(colChangeTo);

    TableColumn<Change, String> colExplicit = new TableColumn<>("Explicit or implicit?");
    colExplicit.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getDataset().isChangeImplicit(features.getValue()) ? "Implicit"
                            : "Explicit"));
    tv.getColumns().add(colExplicit);

    ChangeFilter cf = datasetView.getProjectView().getProject().getChangeFilter();
    TableColumn<Change, String> colFiltered = new TableColumn<>("Eliminated by filter?");
    colFiltered.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    cf.test(features.getValue()) ? "Allowed" : "Eliminated"));
    tv.getColumns().add(colFiltered);

    TableColumn<Change, String> colNote = new TableColumn<>("Note");
    colNote.setCellFactory(TextFieldTableCell.forTableColumn());
    colNote.setCellValueFactory(new PropertyValueFactory<>("note"));
    colNote.setPrefWidth(100.0);
    colNote.setEditable(true);
    tv.getColumns().add(colNote);

    TableColumn<Change, String> colCitations = new TableColumn<>("Citations");
    colCitations.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted()
                            .collect(Collectors.joining("; "))));
    tv.getColumns().add(colCitations);

    TableColumn<Change, String> colGenera = new TableColumn<>("Genera");
    colGenera.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus())
                            .distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colGenera);

    TableColumn<Change, String> colSpecificEpithet = new TableColumn<>("Specific epithets");
    colSpecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(String
                    .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet())
                            .filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colSpecificEpithet);

    // The infraspecific string.
    TableColumn<Change, String> colInfraspecificEpithet = new TableColumn<>("Infraspecific epithets");
    colInfraspecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ",
                            features.getValue().getAllNames().stream()
                                    .map(n -> n.getInfraspecificEpithetsAsString()).filter(s -> s != null)
                                    .distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colInfraspecificEpithet);

    // The very last epithet of all
    TableColumn<Change, String> colTerminalEpithet = new TableColumn<>("Terminal epithet");
    colTerminalEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> {
                        List<Name.InfraspecificEpithet> infraspecificEpithets = n.getInfraspecificEpithets();
                        if (!infraspecificEpithets.isEmpty()) {
                            return infraspecificEpithets.get(infraspecificEpithets.size() - 1).getValue();
                        } else {
                            return n.getSpecificEpithet();
                        }
                    }).filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colTerminalEpithet);

    // Properties
    TableColumn<Change, String> colProperties = new TableColumn<>("Properties");
    colProperties.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getProperties().entrySet().stream()
                            .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted()
                            .collect(Collectors.joining("; "))));
    tv.getColumns().add(colProperties);

    fillTableWithChanges(tv, tp);

    // When someone selects a cell in the Table, try to select the appropriate data in the
    // additional data view.
    tv.getSelectionModel().getSelectedItems().addListener((ListChangeListener<Change>) lcl -> {
        AdditionalData aData = additionalDataCombobox.getSelectionModel().getSelectedItem();

        if (aData != null) {
            aData.onSelectChange(tv.getSelectionModel().getSelectedItems());
        }
    });

    // Create a right-click menu for table rows.
    changesTableView.setRowFactory(table -> {
        TableRow<Change> row = new TableRow<>();

        row.setOnContextMenuRequested(event -> {
            if (row.isEmpty())
                return;

            // We don't currently use the clicked change, since currently all options
            // change *all* the selected changes, but this may change in the future.
            Change change = row.getItem();

            ContextMenu changeMenu = new ContextMenu();

            Menu searchForName = new Menu("Search for name");
            searchForName.getItems().addAll(
                    change.getAllNames().stream().sorted().map(n -> createMenuItem(n.getFullName(), action -> {
                        datasetView.getProjectView().openDetailedView(n);
                    })).collect(Collectors.toList()));
            changeMenu.getItems().add(searchForName);
            changeMenu.getItems().add(new SeparatorMenuItem());

            changeMenu.getItems().add(createMenuItem("Edit note", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());

                String combinedNotes = changes.stream().map(ch -> ch.getNote().orElse("").trim()).distinct()
                        .collect(Collectors.joining("\n")).trim();

                Optional<String> result = askUserForTextArea(
                        "Modify the note for these " + changes.size() + " changes:", combinedNotes);

                if (result.isPresent()) {
                    String note = result.get().trim();
                    LOGGER.info("Using 'Edit note' to set note to '" + note + "' on changes " + changes);
                    changes.forEach(ch -> ch.noteProperty().set(note));
                }
            }));
            changeMenu.getItems().add(new SeparatorMenuItem());

            // Create a submenu for tags and urls.
            String note = change.noteProperty().get();

            Menu removeTags = new Menu("Tags");
            removeTags.getItems().addAll(change.getTags().stream().sorted()
                    .map(tag -> new MenuItem(tag.getName())).collect(Collectors.toList()));

            Menu lookupURLs = new Menu("Lookup URL");
            change.getURIs().stream().sorted().map(uri -> {
                return createMenuItem(uri.toString(), evt -> {
                    try {
                        Desktop.getDesktop().browse(uri);
                    } catch (IOException ex) {
                        LOGGER.warning("Could not open URL '" + uri + "': " + ex);
                    }
                });
            }).forEach(mi -> lookupURLs.getItems().add(mi));
            changeMenu.getItems().add(lookupURLs);

            changeMenu.getItems().add(new SeparatorMenuItem());
            changeMenu.getItems().add(createMenuItem("Prepend text to all notes", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());

                Optional<String> result = askUserForTextField(
                        "Enter tags to prepend to notes in " + changes.size() + " changes:");

                if (result.isPresent()) {
                    String tags = result.get().trim();
                    changes.forEach(ch -> {
                        String prevValue = change.getNote().orElse("").trim();

                        LOGGER.info("Prepending tags '" + tags + "' to previous value '" + prevValue
                                + "' for change " + ch);

                        ch.noteProperty().set((tags + " " + prevValue).trim());
                    });
                }
            }));
            changeMenu.getItems().add(createMenuItem("Append text to all notes", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());
                Optional<String> result = askUserForTextField(
                        "Enter tags to append to notes in " + changes.size() + " changes:");

                if (result.isPresent()) {
                    String tags = result.get().trim();
                    changes.forEach(ch -> {
                        String prevValue = ch.getNote().orElse("").trim();

                        LOGGER.info("Appending tags '" + tags + "' to previous value '" + prevValue
                                + "' for change " + ch);

                        ch.noteProperty().setValue((prevValue + " " + tags).trim());
                    });
                }
            }));

            changeMenu.show(datasetView.getScene().getWindow(), event.getScreenX(), event.getScreenY());

        });

        return row;
    });

    LOGGER.info("setupTableWithChanges() completed");
}

From source file:calendarioSeries.vistas.MainViewController.java

public void populateImagenes() {
    Platform.runLater(new Runnable() {
        @Override// w  ww .  j a v  a 2 s . co  m
        public void run() {
            imagenes.getChildren().clear();
            for (Serie serie : series) {
                //System.out.println(serie.getLastVisto());
                try {
                    Image image = new Image(serie.getUrlImagen());
                    ImageView poster = new ImageView();
                    ContextMenu menu = new ContextMenu();
                    //String css = MainApp.class.getResource("resources/MainTheme.css").toExternalForm();
                    MenuItem delete = new MenuItem("Eliminar");
                    delete.setId(serie.getId());
                    delete.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent event) {
                            menu.hide();
                            MenuItem clicked = (MenuItem) event.getSource();
                            String toDelete = clicked.getId();
                            for (Serie serie : series) {
                                if (serie.getId().equals(toDelete)) {
                                    series.remove(serie);
                                    populateImagenes();
                                    showDetallesMes(mesActual);
                                }
                            }
                            event.consume();
                        }
                    });

                    menu.getItems().add(delete);

                    poster.setId(serie.getTitulo());
                    poster.setImage(image);
                    poster.setCache(true);
                    // poster.setPreserveRatio(true);
                    poster.setFitWidth(210);
                    poster.setFitHeight(300);
                    poster.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
                        @Override
                        public void handle(ContextMenuEvent event) {
                            menu.show(poster, event.getScreenX(), event.getScreenY());
                            //menu.getScene().getRoot().getStylesheets().add(css);
                            event.consume();
                        }
                    });
                    poster.setOnMouseClicked(new EventHandler<MouseEvent>() {
                        @Override
                        public void handle(MouseEvent event) {
                            if (event.getButton() == MouseButton.PRIMARY) {
                                try {
                                    //serieToPass = serie;
                                    sceneToPass = mainApp.scene;

                                    FXMLLoader loader = new FXMLLoader(
                                            getClass().getResource("DetailsSerieController.fxml"));
                                    Parent root = loader.load();
                                    DetailsSerieController controller = loader.getController();
                                    controller.setData(serie, series);
                                    controller.setMainApp(mainApp);

                                    Scene scene = new Scene(root);
                                    mainApp.primaryStage.setScene(scene);
                                    mainApp.primaryStage.show();
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                }
                            }
                        }

                    });
                    imagenes.getChildren().add(poster);
                } catch (IllegalArgumentException e) {
                    Image image = new Image("file:src/calendarioSeries/resources/no-image.png");
                    ImageView poster = new ImageView();
                    ContextMenu menu = new ContextMenu();
                    MenuItem delete = new MenuItem("Eliminar");
                    delete.setId(serie.getId());
                    delete.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent event) {
                            menu.hide();
                            MenuItem clicked = (MenuItem) event.getSource();
                            String toDelete = clicked.getId();
                            for (Serie serie : series) {
                                if (serie.getId().equals(toDelete)) {
                                    series.remove(serie);
                                    populateImagenes();
                                    showDetallesMes(mesActual);
                                }
                            }
                            event.consume();
                        }
                    });

                    menu.getItems().add(delete);

                    poster.setId(serie.getTitulo());
                    poster.setImage(image);
                    poster.setCache(true);
                    //poster.setPreserveRatio(true);
                    poster.setFitWidth(210);
                    poster.setFitHeight(300);
                    poster.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
                        @Override
                        public void handle(ContextMenuEvent event) {
                            menu.show(poster, event.getScreenX(), event.getScreenY());
                            event.consume();
                        }
                    });
                    Text text = new Text(serie.getTitulo());
                    text.getStyleClass().add("label");
                    StackPane pane = new StackPane();
                    pane.getChildren().addAll(poster, text);

                    imagenes.getChildren().add(pane);
                } finally {
                    rellenarArchivo();
                }
            }
        }
    });

}

From source file:net.sourceforge.pmd.util.fxdesigner.XPathPanelController.java

private void initGenerateXPathFromStackTrace() {

    ContextMenu menu = new ContextMenu();

    MenuItem item = new MenuItem("Generate from stack trace...");
    item.setOnAction(e -> {/*from ww  w  .  ja va  2  s .  c o  m*/
        try {
            Stage popup = new Stage();
            FXMLLoader loader = new FXMLLoader(DesignerUtil.getFxml("generate-xpath-from-stack-trace.fxml"));
            Parent root = loader.load();
            Button button = (Button) loader.getNamespace().get("generateButton");
            TextArea area = (TextArea) loader.getNamespace().get("stackTraceArea");

            ValidationSupport validation = new ValidationSupport();

            validation.registerValidator(area,
                    Validator.createEmptyValidator("The stack trace may not be empty"));
            button.disableProperty().bind(validation.invalidProperty());

            button.setOnAction(f -> {
                DesignerUtil.stackTraceToXPath(area.getText()).ifPresent(xpathExpressionArea::replaceText);
                popup.close();
            });

            popup.setScene(new Scene(root));
            popup.initStyle(StageStyle.UTILITY);
            popup.initModality(Modality.WINDOW_MODAL);
            popup.initOwner(designerRoot.getMainStage());
            popup.show();
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    });

    menu.getItems().add(item);

    xpathExpressionArea.addEventHandler(MouseEvent.MOUSE_CLICKED, t -> {
        if (t.getButton() == MouseButton.SECONDARY) {
            menu.show(xpathExpressionArea, t.getScreenX(), t.getScreenY());
        }
    });
}

From source file:de.hs.mannheim.modUro.controller.diagram.fx.ChartViewer.java

/**
 * Creates the context menu.//  w w  w  .  ja  v  a  2 s .  c o  m
 *
 * @return The context menu.
 */
private ContextMenu createContextMenu() {
    final ContextMenu menu = new ContextMenu();

    Menu export = new Menu("Export As");

    MenuItem pngItem = new MenuItem("PNG ...");
    pngItem.setOnAction((ActionEvent e) -> {
        handleExportToPNG();
    });
    export.getItems().add(pngItem);

    MenuItem jpegItem = new MenuItem("JPEG ...");
    jpegItem.setOnAction((ActionEvent e) -> {
        handleExportToJPEG();
    });
    export.getItems().add(jpegItem);

    MenuItem tikzItem = new MenuItem("Tikz ...");
    tikzItem.setOnAction((ActionEvent e) -> {
        handleExportToTikz();
    });
    export.getItems().add(tikzItem);

    MenuItem wsvItem = new MenuItem("Text  ...");
    wsvItem.setOnAction((ActionEvent e) -> {
        handleExportToWSV();
    });
    export.getItems().add(wsvItem);

    if (ExportUtils.isOrsonPDFAvailable()) {
        MenuItem pdfItem = new MenuItem("PDF ...");
        pdfItem.setOnAction((ActionEvent e) -> {
            handleExportToPDF();
        });
        export.getItems().add(pdfItem);
    }
    if (ExportUtils.isJFreeSVGAvailable()) {
        MenuItem svgItem = new MenuItem("SVG...");
        svgItem.setOnAction((ActionEvent e) -> {
            handleExportToSVG();
        });
        export.getItems().add(svgItem);
    }
    menu.getItems().add(export);
    return menu;
}

From source file:com.ggvaidya.scinames.dataset.BinomialChangesSceneController.java

private void setupTableWithBinomialChanges() {
    changesTableView.setEditable(false);
    changesTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    changesTableView.setItems(potentialChanges);

    changesTableView.getColumns().clear();

    TableColumn<PotentialChange, ChangeType> colChangeType = new TableColumn<>("Type");
    colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(),
            ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT,
            ChangeType.COMPLEX, ChangeType.ERROR));
    colChangeType.setCellValueFactory(new PropertyValueFactory<>("type"));
    colChangeType.setPrefWidth(100.0);//from  w w w. ja v a2 s .c om
    colChangeType.setEditable(true);
    changesTableView.getColumns().add(colChangeType);

    TableColumn<PotentialChange, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From");
    colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from"));
    colChangeFrom.setPrefWidth(200.0);
    colChangeFrom.setEditable(true);
    changesTableView.getColumns().add(colChangeFrom);

    TableColumn<PotentialChange, ObservableSet<Name>> colChangeTo = new TableColumn<>("To");
    colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to"));
    colChangeTo.setPrefWidth(200.0);
    colChangeTo.setEditable(true);
    changesTableView.getColumns().add(colChangeTo);

    TableColumn<PotentialChange, String> colDataset = new TableColumn<>("Dataset");
    colDataset.setCellValueFactory(cvf -> {
        return new ReadOnlyStringWrapper(cvf.getValue().getDataset().toString());
    });
    colDataset.setPrefWidth(150.0);
    changesTableView.getColumns().add(colDataset);

    TableColumn<PotentialChange, SimplifiedDate> dateCol = new TableColumn<>("Date");
    dateCol.setCellFactory(
            TextFieldTableCell.forTableColumn(new SimplifiedDate.SimplifiedDateStringConverter()));
    dateCol.setCellValueFactory(cvf -> new ReadOnlyObjectWrapper<>(cvf.getValue().getDataset().getDate()));
    dateCol.setPrefWidth(150);
    dateCol.setSortable(true);
    dateCol.setSortType(SortType.ASCENDING);
    changesTableView.getColumns().add(dateCol);
    changesTableView.getSortOrder().add(dateCol);

    TableColumn<PotentialChange, String> colChangeSummary = new TableColumn<>("Changes summary");
    colChangeSummary.setCellValueFactory(cvf -> {
        Set<Change> changes = changesByPotentialChange.get(cvf.getValue());
        return new ReadOnlyStringWrapper(changes.size() + ": "
                + changes.stream().map(ch -> ch.toString()).collect(Collectors.joining("; ")));
    });
    colChangeSummary.setPrefWidth(200.0);
    changesTableView.getColumns().add(colChangeSummary);

    /*
    TableColumn<PotentialChange, String> colExplicit = new TableColumn<>("Explicit or implicit?");
    colExplicit.setCellValueFactory(
       (TableColumn.CellDataFeatures<Change, String> features) -> 
    new ReadOnlyStringWrapper(
       features.getValue().getDataset().isChangeImplicit(features.getValue()) ? "Implicit" : "Explicit"
    )
    );
    tv.getColumns().add(colExplicit);
            
    ChangeFilter cf = binomialChangesView.getProjectView().getProject().getChangeFilter();
    TableColumn<Change, String> colFiltered = new TableColumn<>("Eliminated by filter?");
    colFiltered.setCellValueFactory(
       (TableColumn.CellDataFeatures<Change, String> features) -> 
    new ReadOnlyStringWrapper(
       cf.test(features.getValue()) ? "Allowed" : "Eliminated"
    )
    );
    tv.getColumns().add(colFiltered);
    */

    TableColumn<PotentialChange, String> colNote = new TableColumn<>("Note");
    colNote.setCellFactory(TextFieldTableCell.forTableColumn());
    colNote.setCellValueFactory(new PropertyValueFactory<>("note"));
    colNote.setPrefWidth(100.0);
    changesTableView.getColumns().add(colNote);

    TableColumn<PotentialChange, String> colReason = new TableColumn<>("Reason");
    colReason.setCellValueFactory(cvf -> new ReadOnlyStringWrapper(calculateReason(cvf.getValue())));
    colReason.setPrefWidth(100.0);
    changesTableView.getColumns().add(colReason);

    TableColumn<PotentialChange, String> colReasonDate = new TableColumn<>("ReasonDate");
    colReasonDate.setCellValueFactory(cvf -> {
        String result;
        Set<SimplifiedDate> dates = calculateReasonDate(cvf.getValue());

        if (dates.size() > 1) {
            result = "(" + dates.size() + ") " + dates.stream().distinct().sorted()
                    .map(sd -> sd.asYYYYmmDD("-")).collect(Collectors.joining("|"));

        } else if (dates.size() == 1) {
            result = dates.iterator().next().asYYYYmmDD("-");

        } else {
            result = "NA";
        }

        return new ReadOnlyStringWrapper(result);
    });
    colReasonDate.setPrefWidth(100.0);
    changesTableView.getColumns().add(colReasonDate);

    TableColumn<PotentialChange, String> colCitations = new TableColumn<>("Citations");
    colCitations.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted()
                            .collect(Collectors.joining("; "))));
    changesTableView.getColumns().add(colCitations);

    TableColumn<PotentialChange, String> colGenera = new TableColumn<>("Genera");
    colGenera.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus())
                            .distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colGenera);

    TableColumn<PotentialChange, String> colSpecificEpithet = new TableColumn<>("Specific epithets");
    colSpecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(String
                    .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet())
                            .filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colSpecificEpithet);

    // The infraspecific string.
    TableColumn<PotentialChange, String> colInfraspecificEpithet = new TableColumn<>("Infraspecific epithets");
    colInfraspecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ",
                            features.getValue().getAllNames().stream()
                                    .map(n -> n.getInfraspecificEpithetsAsString()).filter(s -> s != null)
                                    .distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colInfraspecificEpithet);

    // The very last epithet of all
    TableColumn<PotentialChange, String> colTerminalEpithet = new TableColumn<>("Terminal epithet");
    colTerminalEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> {
                        List<Name.InfraspecificEpithet> infraspecificEpithets = n.getInfraspecificEpithets();
                        if (!infraspecificEpithets.isEmpty()) {
                            return infraspecificEpithets.get(infraspecificEpithets.size() - 1).getValue();
                        } else {
                            return n.getSpecificEpithet();
                        }
                    }).filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colTerminalEpithet);

    TableColumn<PotentialChange, String> dateForRCol = new TableColumn<>("DateYMD");
    dateForRCol.setCellValueFactory(
            cvf -> new ReadOnlyObjectWrapper<>(cvf.getValue().getDataset().getDate().asYYYYmmDD("-")));
    changesTableView.getColumns().add(dateForRCol);

    // Properties
    TableColumn<PotentialChange, String> colProperties = new TableColumn<>("Properties");
    colProperties.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getProperties().entrySet().stream()
                            .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted()
                            .collect(Collectors.joining("; "))));
    changesTableView.getColumns().add(colProperties);

    fillTableWithBinomialChanges();

    // When someone selects a cell in the Table, try to select the appropriate data in the
    // additional data view.
    changesTableView.getSelectionModel().getSelectedItems()
            .addListener((ListChangeListener<PotentialChange>) lcl -> {
                AdditionalData aData = additionalDataCombobox.getSelectionModel().getSelectedItem();

                if (aData != null) {
                    aData.onSelectChange(changesTableView.getSelectionModel().getSelectedItems());
                }
            });

    // Create a right-click menu for table rows.
    changesTableView.setRowFactory(table -> {
        TableRow<PotentialChange> row = new TableRow<>();

        row.setOnContextMenuRequested(event -> {
            if (row.isEmpty())
                return;

            // We don't currently use the clicked change, since currently all options
            // change *all* the selected changes, but this may change in the future.
            PotentialChange change = row.getItem();

            ContextMenu changeMenu = new ContextMenu();

            Menu lookupChange = new Menu("Look up change");
            lookupChange.getItems().addAll(changesByPotentialChange.getOrDefault(change, new HashSet<>())
                    .stream()
                    .map(ch -> createMenuItem(ch.toString() + " in " + ch.getDataset().toString(), action -> {
                        binomialChangesView.getProjectView().openDetailedView(ch);
                    })).collect(Collectors.toList()));
            changeMenu.getItems().add(lookupChange);

            changeMenu.getItems().add(new SeparatorMenuItem());

            Menu searchForName = new Menu("Search for name");
            searchForName.getItems().addAll(
                    change.getAllNames().stream().sorted().map(n -> createMenuItem(n.getFullName(), action -> {
                        binomialChangesView.getProjectView().openDetailedView(n);
                    })).collect(Collectors.toList()));
            changeMenu.getItems().add(searchForName);

            changeMenu.getItems().add(new SeparatorMenuItem());

            // Create a submenu for tags and urls.
            String note = change.noteProperty().get();

            Menu removeTags = new Menu("Tags");
            removeTags.getItems().addAll(change.getTags().stream().sorted()
                    .map(tag -> new MenuItem(tag.getName())).collect(Collectors.toList()));

            Menu lookupURLs = new Menu("Lookup URL");
            change.getURIs().stream().sorted().map(uri -> {
                return createMenuItem(uri.toString(), evt -> {
                    try {
                        Desktop.getDesktop().browse(uri);
                    } catch (IOException ex) {
                        LOGGER.warning("Could not open URL '" + uri + "': " + ex);
                    }
                });
            }).forEach(mi -> lookupURLs.getItems().add(mi));
            changeMenu.getItems().add(lookupURLs);

            changeMenu.show(binomialChangesView.getScene().getWindow(), event.getScreenX(), event.getScreenY());

        });

        return row;
    });

    LOGGER.info("setupTableWithChanges() completed");
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

@FXML
public void initialize() {
    this.rootItem = new TreeItem<>(new TreeNode("[root]"));
    this.root.setRoot(this.rootItem);
    this.root.setCellFactory(new TreeCellFactory<>(node -> {
        if (node.getParent() == null) {
            ContextMenu export = new ContextMenu();

            MenuItem exportItem = new MenuItem("Export");

            export.setOnAction(e -> {
                File file = messageHandler.chooseFile().withInitialDirectory(new File("."))
                        .withTitle(Message.GENERIC_CHOOSE_EXPORT_LOCATION_JAR.format())
                        .withExtensionFilter(new FileFilter(Message.FILETYPE_JAVA_ARCHIVE.format(), "*.jar"),
                                true)/*from w  ww  .j  ava  2s  . c om*/
                        .promptSave();

                OpenedFile openedFile = (OpenedFile) node.getMetadata().get(OpenedFile.OPENED_FILE);

                Map<String, byte[]> clone = new HashMap<>(openedFile.getContents());

                backgroundTaskHelper.submit(
                        new BackgroundTask(Message.TASK_SAVING_FILE.format(node.getDisplayName()), true, () -> {
                            try {
                                if (!file.exists()) {
                                    if (!file.createNewFile()) {
                                        throw new IOException("Could not create export file");
                                    }
                                }

                                try (ZipOutputStream zipOutputStream = new ZipOutputStream(
                                        new FileOutputStream(file))) {
                                    for (Map.Entry<String, byte[]> ent : clone.entrySet()) {
                                        ZipEntry zipEntry = new ZipEntry(ent.getKey());
                                        zipOutputStream.putNextEntry(zipEntry);
                                        zipOutputStream.write(ent.getValue());
                                        zipOutputStream.closeEntry();
                                    }
                                }

                                messageHandler.handleMessage(Message.GENERIC_EXPORTED.format());
                            } catch (IOException ex) {
                                messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), ex);
                            }
                        }));
            });

            export.getItems().add(exportItem);
            return export;
        }
        return null;
    }));

    root.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
        if (event.getCode() == KeyCode.ENTER) {
            TreeItem<TreeNode> selected = this.root.getSelectionModel().getSelectedItem();
            if (selected != null) {
                if (selected.getChildren().size() != 0) {
                    selected.setExpanded(!selected.isExpanded());
                } else {
                    getParentController().getAllFilesViewerController().handleClick(selected.getValue());
                }
            }
        }
    });

    Tooltip tooltip = new Tooltip();
    StringBuilder search = new StringBuilder();

    List<TreeItem<TreeNode>> searchContext = new ArrayList<>();
    AtomicInteger searchIndex = new AtomicInteger();

    root.focusedProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue) {
            tooltip.hide();
            search.setLength(0);
        }
    });

    root.boundsInLocalProperty().addListener((observable, oldValue, newValue) -> {
        Bounds bounds = root.localToScreen(newValue);
        tooltip.setAnchorX(bounds.getMinX());
        tooltip.setAnchorY(bounds.getMinY());
    });

    root.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
        if (tooltip.isShowing() && event.getCode() == KeyCode.UP) {
            if (searchIndex.decrementAndGet() < 0) {
                searchIndex.set(searchContext.size() - 1);
            }
        } else if (tooltip.isShowing() && event.getCode() == KeyCode.DOWN) {
            if (searchIndex.incrementAndGet() >= searchContext.size()) {
                searchIndex.set(0);
            }
        } else {
            return;
        }
        event.consume();

        root.scrollTo(root.getRow(searchContext.get(searchIndex.get())));
        root.getSelectionModel().select(searchContext.get(searchIndex.get()));
    });

    root.addEventHandler(KeyEvent.KEY_TYPED, event -> {
        if (event.getCharacter().charAt(0) == '\b') {
            if (search.length() > 0) {
                search.setLength(search.length() - 1);
            }
        } else if (event.getCharacter().charAt(0) == '\u001B') { //esc
            tooltip.hide();
            search.setLength(0);
            return;
        } else if (search.length() > 0
                || (search.length() == 0 && StringUtils.isAlphanumeric(event.getCharacter()))) {
            search.append(event.getCharacter());
            if (!tooltip.isShowing()) {
                tooltip.show(root.getScene().getWindow());
            }
        }

        if (!tooltip.isShowing())
            return;

        String str = search.toString();
        tooltip.setText("Search for: " + str);

        searchContext.clear();

        ArrayDeque<TreeItem<TreeNode>> deque = new ArrayDeque<>();
        deque.addAll(rootItem.getChildren());

        while (!deque.isEmpty()) {
            TreeItem<TreeNode> item = deque.poll();
            if (item.getValue().getDisplayName().contains(str)) {
                searchContext.add(item);
            }
            if (item.isExpanded() && item.getChildren().size() > 0)
                deque.addAll(item.getChildren());
        }

        searchIndex.set(0);
        if (searchContext.size() > 0) {
            root.scrollTo(root.getRow(searchContext.get(0)));
            root.getSelectionModel().select(searchContext.get(0));
        }
    });

    openedFileController.loadedFiles().addListener((MapChangeListener<String, OpenedFile>) change -> {
        if (change.getValueAdded() != null) {
            updateTree(change.getValueAdded());
        }
        if (change.getValueRemoved() != null) {
            this.rootItem.getChildren()
                    .removeIf(ti -> ti.getValue().equals(change.getValueRemoved().getRoot()));
        }
    });
}