Example usage for javafx.scene.control ContextMenu ContextMenu

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

Introduction

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

Prototype

public ContextMenu() 

Source Link

Document

Create a new ContextMenu

Usage

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  ww .j av  a  2  s. c o 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:calendarioSeries.vistas.MainViewController.java

public void populateImagenes() {
    Platform.runLater(new Runnable() {
        @Override/*from w w  w  .j av a2s  .c o 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:fr.amap.commons.javafx.chart.ChartViewer.java

private ContextMenu createContextMenu() {

    menu = new ContextMenu();

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

    MenuItem pngItem = new MenuItem("PNG...");
    pngItem.setOnAction((ActionEvent e) -> {
        handleExportToPNG();//from   w  ww  . j a v a  2  s  .c o  m
    });
    export.getItems().add(pngItem);

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

    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:be.makercafe.apps.makerbench.Main.java

private ContextMenu createViewerContextMenu() {

    ContextMenu rootContextMenu = new ContextMenu();
    // Add Folder..
    MenuItem addFolder = new MenuItem("Add folder..");
    addFolder.setOnAction(new EventHandler<ActionEvent>() {

        @Override//from w  w  w  . java 2  s  .  com
        public void handle(ActionEvent event) {
            TextInputDialog dialog = new TextInputDialog("myfolder");
            dialog.setTitle("New folder");
            dialog.setHeaderText("Create a new folder");
            dialog.setContentText("Folder name:");
            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()) {
                ResourceTreeItem<String> item = (ResourceTreeItem<String>) viewer.getSelectionModel()
                        .getSelectedItem();

                File file = new File(
                        item.getPath().toFile().getAbsolutePath() + File.separatorChar + result.get());
                if (!file.exists()) {
                    if (!file.mkdir()) {
                        Alert alert = new Alert(AlertType.ERROR);
                        alert.setTitle("Error Dialog");
                        alert.setHeaderText("Error occured while creating folder");
                        alert.setContentText("Folder path: " + file.getAbsolutePath());
                        alert.showAndWait();
                    } else {
                        viewer.setRoot(setRootFolder(new File(pathMakerbenchHome)));
                    }
                }

            }
        }
    });

    // Delete folder
    MenuItem deleteFolder = new MenuItem("Delete folder..");
    deleteFolder.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle("Confirmation Dialog");
            alert.setHeaderText("Delete folder");
            alert.setContentText("Please confirm deleteion of selected folder and all it's contents ?");

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == ButtonType.OK) {
                ResourceTreeItem<String> item = (ResourceTreeItem<String>) viewer.getSelectionModel()
                        .getSelectedItem();
                File file = new File(item.getPath().toFile().getAbsolutePath());
                if (file.exists()) {
                    try {
                        FileUtils.deleteDirectory(file);
                        viewer.setRoot(setRootFolder(new File(pathMakerbenchHome)));
                    } catch (Exception e) {
                        alert = new Alert(AlertType.ERROR);
                        alert.setTitle("Error Dialog");
                        alert.setHeaderText("Error occured while deleting folder");
                        alert.setContentText("Error messsage: " + e.getMessage());
                        alert.showAndWait();
                    }

                }

            }
        }
    });

    // Add File..
    MenuItem addFile = new MenuItem("Add file..");
    addFile.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            TextInputDialog dialog = new TextInputDialog("myfile.txt");
            dialog.setTitle("New file");
            dialog.setHeaderText("Create a new file (.jfxscad, .jfxmill, .txt, .md, .xml, .gcode");
            dialog.setContentText("File name:");
            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()) {
                ResourceTreeItem<String> item = (ResourceTreeItem<String>) viewer.getSelectionModel()
                        .getSelectedItem();

                File file = new File(
                        item.getPath().toFile().getAbsolutePath() + File.separatorChar + result.get());
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                        viewer.setRoot(setRootFolder(new File(pathMakerbenchHome)));
                    } catch (Exception e) {
                        Alert alert = new Alert(AlertType.ERROR);
                        alert.setTitle("Error Dialog");
                        alert.setHeaderText("Error occured while creating file");
                        alert.setContentText(
                                "File path: " + file.getAbsolutePath() + "\nError message: " + e.getMessage());
                        alert.showAndWait();
                    }
                }

            }
        }
    });

    // Delete file
    MenuItem deleteFile = new MenuItem("Delete file..");
    deleteFile.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle("Confirmation Dialog");
            alert.setHeaderText("Delete file");
            alert.setContentText("Please confirm deleteion of selected file");

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == ButtonType.OK) {
                ResourceTreeItem<String> item = (ResourceTreeItem<String>) viewer.getSelectionModel()
                        .getSelectedItem();
                File file = new File(item.getPath().toFile().getAbsolutePath());
                if (file.exists()) {

                    if (!file.delete()) {

                        alert = new Alert(AlertType.ERROR);
                        alert.setTitle("Error Dialog");
                        alert.setHeaderText("Error occured while deleting file");
                        alert.setContentText("File path: " + file.getAbsolutePath());
                        alert.showAndWait();
                    } else {
                        viewer.setRoot(setRootFolder(new File(pathMakerbenchHome)));
                    }

                }

            }
        }
    });
    rootContextMenu.getItems().addAll(addFolder, deleteFolder, addFile, deleteFile);
    return rootContextMenu;
}

From source file:dtv.controller.FXMLMainController.java

public void init(ObservableList<DVBChannel> serviceData, TableView<DVBChannel> table,
        TableColumn<DVBChannel, Integer> idx, TableColumn<DVBChannel, String> name,
        TableColumn<DVBChannel, String> type, TableColumn<DVBChannel, String> ppr) {

    table.setEditable(true);/*from  w  w w  . j  a  va 2s  .c o  m*/
    idx.setCellValueFactory(cellData -> cellData.getValue().idxProperty().asObject());
    name.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
    name.setEditable(true);
    type.setCellValueFactory(cellData -> cellData.getValue().typeProperty());
    // nid.setCellValueFactory(cellData -> cellData.getValue().nidProperty().asObject());
    ppr.setCellValueFactory(cellData -> cellData.getValue().pprProperty());
    // newCol.setCellValueFactory(cellData -> cellData.getValue().neewProperty());

    // Context menu
    table.setRowFactory(tableView -> {
        final TableRow<DVBChannel> row = new TableRow<>();
        final ContextMenu rowMenu = new ContextMenu();

        final MenuItem removeItem = new MenuItem("Delete");
        removeItem.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final DVBChannel service = row.getItem();
                serviceData.removeAll(service);
            }
        });

        rowMenu.getItems().addAll(removeItem);
        row.contextMenuProperty().bind(Bindings.when(Bindings.isNotNull(row.itemProperty())).then(rowMenu)
                .otherwise((ContextMenu) null));

        return row;
    });

    ppr.setCellFactory(col -> {
        final TableCell<DVBChannel, String> cell = new TableCell<>();

        cell.textProperty().bind(cell.itemProperty());
        cell.itemProperty().addListener((obs, oldValue, newValue) -> {
            if (newValue != null) {
                final ContextMenu cellMenu = new ContextMenu();
                for (String pref : Utils.prefTab) {
                    final CheckMenuItem prefMenuItem = new CheckMenuItem(pref);

                    if (Utils.isPreferenceOn(cell.getText(), pref)) {
                        prefMenuItem.setSelected(true);
                    }

                    prefMenuItem.selectedProperty().addListener((obs1, old_val, new_val) -> {
                        final String new_ppr;
                        final DVBChannel service = (DVBChannel) cell.getTableRow().getItem();

                        if (new_val) {
                            new_ppr = Utils.add_ppr(cell.getText(), pref);
                        } else {
                            new_ppr = Utils.remove_ppr(cell.getText(), pref);
                        }

                        service.setPpr(new_ppr);
                        service.setModified(true);
                    });

                    cellMenu.getItems().add(prefMenuItem);
                    cell.setContextMenu(cellMenu);
                }
            } else {
                cell.setContextMenu(null);
            }
        });
        return cell;
    });

    // Editable service name
    name.setCellFactory(p -> new EditingCell());

    name.setOnEditCommit(t -> {

        final DVBChannel service = t.getTableView().getItems().get(t.getTablePosition().getRow());
        service.setName(t.getNewValue());
        service.setModified(true);
    });
}

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

/**
 * descriptionReader is optional//from   w  w w. ja va 2  s .c om
 */
public ConceptNode(ConceptVersionBI initialConcept, boolean flagAsInvalidWhenBlank,
        ObservableList<SimpleDisplayConcept> dropDownOptions,
        Function<ConceptVersionBI, String> descriptionReader) {
    c_ = initialConcept;
    //We can't simply use the ObservableList from the CommonlyUsedConcepts, because it infinite loops - there doesn't seem to be a way 
    //to change the items in the drop down without changing the selection.  So, we have this hack instead.
    listChangeListener_ = new ListChangeListener<SimpleDisplayConcept>() {
        @Override
        public void onChanged(Change<? extends SimpleDisplayConcept> c) {
            //TODO I still have an infinite loop here.  Find and fix.
            logger.debug("updating concept dropdown");
            disableChangeListener_ = true;
            SimpleDisplayConcept temp = cb_.getValue();
            cb_.setItems(FXCollections.observableArrayList(dropDownOptions_));
            cb_.setValue(temp);
            cb_.getSelectionModel().select(temp);
            disableChangeListener_ = false;
        }
    };
    descriptionReader_ = (descriptionReader == null ? (conceptVersion) -> {
        return conceptVersion == null ? "" : OTFUtility.getDescription(conceptVersion);
    } : descriptionReader);
    dropDownOptions_ = dropDownOptions == null
            ? AppContext.getService(CommonlyUsedConcepts.class).getObservableConcepts()
            : dropDownOptions;
    dropDownOptions_.addListener(new WeakListChangeListener<SimpleDisplayConcept>(listChangeListener_));
    conceptBinding_ = new ObjectBinding<ConceptVersionBI>() {
        @Override
        protected ConceptVersionBI computeValue() {
            return c_;
        }
    };

    flagAsInvalidWhenBlank_ = flagAsInvalidWhenBlank;
    cb_ = new ComboBox<>();
    cb_.setConverter(new StringConverter<SimpleDisplayConcept>() {
        @Override
        public String toString(SimpleDisplayConcept object) {
            return object == null ? "" : object.getDescription();
        }

        @Override
        public SimpleDisplayConcept fromString(String string) {
            return new SimpleDisplayConcept(string, 0);
        }
    });
    cb_.setValue(new SimpleDisplayConcept("", 0));
    cb_.setEditable(true);
    cb_.setMaxWidth(Double.MAX_VALUE);
    cb_.setPrefWidth(ComboBox.USE_COMPUTED_SIZE);
    cb_.setMinWidth(200.0);
    cb_.setPromptText("Type, drop or select a concept");

    cb_.setItems(FXCollections.observableArrayList(dropDownOptions_));
    cb_.setVisibleRowCount(11);

    cm_ = new ContextMenu();

    MenuItem copyText = new MenuItem("Copy Description");
    copyText.setGraphic(Images.COPY.createImageView());
    copyText.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            CustomClipboard.set(cb_.getEditor().getText());
        }
    });
    cm_.getItems().add(copyText);

    CommonMenusNIdProvider nidProvider = new CommonMenusNIdProvider() {
        @Override
        public Set<Integer> getNIds() {
            Set<Integer> nids = new HashSet<>();
            if (c_ != null) {
                nids.add(c_.getNid());
            }
            return nids;
        }
    };
    CommonMenuBuilderI menuBuilder = CommonMenus.CommonMenuBuilder.newInstance();
    menuBuilder.setInvisibleWhenFalse(isValid);
    CommonMenus.addCommonMenus(cm_, menuBuilder, nidProvider);

    cb_.getEditor().setContextMenu(cm_);

    updateGUI();

    new LookAheadConceptPopup(cb_);

    if (cb_.getValue().getNid() == 0) {
        if (flagAsInvalidWhenBlank_) {
            isValid.setInvalid("Concept Required");
        }
    } else {
        isValid.setValid();
    }

    cb_.valueProperty().addListener(new ChangeListener<SimpleDisplayConcept>() {
        @Override
        public void changed(ObservableValue<? extends SimpleDisplayConcept> observable,
                SimpleDisplayConcept oldValue, SimpleDisplayConcept newValue) {
            if (newValue == null) {
                logger.debug("Combo Value Changed - null entry");
            } else {
                logger.debug("Combo Value Changed: {} {}", newValue.getDescription(), newValue.getNid());
            }

            if (disableChangeListener_) {
                logger.debug("change listener disabled");
                return;
            }

            if (newValue == null) {
                //This can happen if someone calls clearSelection() - it passes in a null.
                cb_.setValue(new SimpleDisplayConcept("", 0));
                return;
            } else {
                if (newValue.shouldIgnoreChange()) {
                    logger.debug("One time change ignore");
                    return;
                }
                //Whenever the focus leaves the combo box editor, a new combo box is generated.  But, the new box will have 0 for an id.  detect and ignore
                if (oldValue != null && oldValue.getDescription().equals(newValue.getDescription())
                        && newValue.getNid() == 0) {
                    logger.debug("Not a real change, ignore");
                    newValue.setNid(oldValue.getNid());
                    return;
                }
                lookup();
            }
        }
    });

    AppContext.getService(DragRegistry.class).setupDragAndDrop(cb_, new SingleConceptIdProvider() {
        @Override
        public String getConceptId() {
            return cb_.getValue().getNid() + "";
        }
    }, true);

    pi_ = new ProgressIndicator(ProgressIndicator.INDETERMINATE_PROGRESS);
    pi_.visibleProperty().bind(isLookupInProgress_);
    pi_.setPrefHeight(16.0);
    pi_.setPrefWidth(16.0);
    pi_.setMaxWidth(16.0);
    pi_.setMaxHeight(16.0);

    lookupFailImage_ = Images.EXCLAMATION.createImageView();
    lookupFailImage_.visibleProperty().bind(isValid.not().and(isLookupInProgress_.not()));
    Tooltip t = new Tooltip();
    t.textProperty().bind(isValid.getReasonWhyInvalid());
    Tooltip.install(lookupFailImage_, t);

    StackPane sp = new StackPane();
    sp.setMaxWidth(Double.MAX_VALUE);
    sp.getChildren().add(cb_);
    sp.getChildren().add(lookupFailImage_);
    sp.getChildren().add(pi_);
    StackPane.setAlignment(cb_, Pos.CENTER_LEFT);
    StackPane.setAlignment(lookupFailImage_, Pos.CENTER_RIGHT);
    StackPane.setMargin(lookupFailImage_, new Insets(0.0, 30.0, 0.0, 0.0));
    StackPane.setAlignment(pi_, Pos.CENTER_RIGHT);
    StackPane.setMargin(pi_, new Insets(0.0, 30.0, 0.0, 0.0));

    hbox_ = new HBox();
    hbox_.setSpacing(5.0);
    hbox_.setAlignment(Pos.CENTER_LEFT);

    hbox_.getChildren().add(sp);
    HBox.setHgrow(sp, Priority.SOMETIMES);
}

From source file:com.exalttech.trex.ui.views.PacketTableView.java

/**
 * Build component UI//from w  w  w .  j  a va  2  s.com
 */
private void buildUI(boolean addExportToYamlBtn) {
    setTopAnchor(this, 0d);
    setLeftAnchor(this, 0d);
    setBottomAnchor(this, 0d);
    setRightAnchor(this, 0d);
    // build btn bar
    HBox buttonContainer = new HBox();
    buttonContainer.setSpacing(5);
    addPacketBtn = new StreamTableButton(StreamTableAction.ADD);
    initializeStreamButtons(addPacketBtn, false);
    buttonContainer.getChildren().add(addPacketBtn);

    // add build stream btn
    buildPacketBtn = new StreamTableButton(StreamTableAction.BUILD);
    buildPacketBtn.setId("buildStreamBtn");
    initializeStreamButtons(buildPacketBtn, false);
    buttonContainer.getChildren().add(buildPacketBtn);

    editPacketBtn = new StreamTableButton(StreamTableAction.EDIT);
    editPacketBtn.setId("editStreanBtn");
    initializeStreamButtons(editPacketBtn, true);
    buttonContainer.getChildren().add(editPacketBtn);

    deleteButtonBtn = new StreamTableButton(StreamTableAction.DELETE);
    initializeStreamButtons(deleteButtonBtn, true);
    buttonContainer.getChildren().add(deleteButtonBtn);

    importPcapButton = new StreamTableButton(StreamTableAction.IMPORT_PCAP);
    initializeStreamButtons(importPcapButton, false);
    buttonContainer.getChildren().add(importPcapButton);

    exportPcapButton = new StreamTableButton(StreamTableAction.EXPORT_TO_PCAP);
    initializeStreamButtons(exportPcapButton, true);
    buttonContainer.getChildren().add(exportPcapButton);

    if (addExportToYamlBtn) {
        exportToYaml = new StreamTableButton(StreamTableAction.EXPORT_TO_YAML);
        initializeStreamButtons(exportToYaml, false);
        buttonContainer.getChildren().add(exportToYaml);
    }
    getChildren().add(buttonContainer);
    setTopAnchor(buttonContainer, 5d);

    rightClickMenu = new ContextMenu();
    addMenuItem(StreamTableAction.EDIT);
    addMenuItem(StreamTableAction.DELETE);
    addMenuItem(StreamTableAction.EXPORT_TO_PCAP);
    addMenuItem(StreamTableAction.EXPORT_TO_YAML);

    // add table view
    streamPacketTableView = new TableView<>();
    streamPacketTableView.setId("streamTableView");
    streamPacketTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    streamPacketTableView.setFixedCellSize(32);
    streamPacketTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    streamPacketTableView.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            handleTableRowClick(event);
        }
    });

    streamPacketTableView.getSelectionModel().selectedItemProperty()
            .addListener((ObservableValue<? extends TableProfileStream> observable, TableProfileStream oldValue,
                    TableProfileStream newValue) -> {
                boolean notSelected = !(newValue != null);

                exportPcapButton.setDisable(notSelected);
                editPacketBtn.setDisable(notSelected);
                deleteButtonBtn.setDisable(notSelected);
            });

    streamPacketTableView.addEventFilter(KeyEvent.KEY_RELEASED, (KeyEvent event) -> {
        if (copyCombination.match(event)) {
            selectedProfile = tabledata.getProfiles()
                    .get(streamPacketTableView.getSelectionModel().getSelectedIndex());
        } else if (pasteCombination.match(event)) {
            handleDuplicateStream();
        } else if (event.getCode() == KeyCode.DELETE) {
            handleDeletePacket();
        }
    });
    streamPacketTableView.setEditable(true);
    initializeTableColumn();
    // disable table reordering
    streamPacketTableView.widthProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> source, Number oldWidth, Number newWidth) {
            TableHeaderRow header = (TableHeaderRow) streamPacketTableView.lookup("TableHeaderRow");
            header.reorderingProperty().addListener(new ChangeListener<Boolean>() {
                @Override
                public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue,
                        Boolean newValue) {
                    header.setReordering(false);
                }
            });
        }
    });

    getChildren().add(streamPacketTableView);
    setTopAnchor(streamPacketTableView, 35d);
    setBottomAnchor(streamPacketTableView, 5d);
    setLeftAnchor(streamPacketTableView, 0d);
    setRightAnchor(streamPacketTableView, 0d);
}

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

/**
 * Creates the context menu./*from  ww  w  . ja  v a 2  s .  c  om*/
 *
 * @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: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 -> {/*ww  w  .  jav a2  s . c om*/
        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:Main.java

@Override
public void start(Stage stage) {
    stage.setTitle("Menu Sample");
    Scene scene = new Scene(new VBox(), 400, 350);
    scene.setFill(Color.OLDLACE);

    name.setFont(new Font("Verdana Bold", 22));
    binName.setFont(new Font("Arial Italic", 10));
    pic.setFitHeight(150);/*  w w  w .  java 2 s . c o m*/
    pic.setPreserveRatio(true);
    description.setWrapText(true);
    description.setTextAlignment(TextAlignment.JUSTIFY);

    shuffle();

    MenuBar menuBar = new MenuBar();

    // --- Graphical elements
    final VBox vbox = new VBox();
    vbox.setAlignment(Pos.CENTER);
    vbox.setSpacing(10);
    vbox.setPadding(new Insets(0, 10, 0, 10));
    vbox.getChildren().addAll(name, binName, pic, description);

    // --- Menu File
    Menu menuFile = new Menu("File");
    MenuItem add = new MenuItem("Shuffle", new ImageView(new Image("src/menusample/new.png")));
    add.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            shuffle();
            vbox.setVisible(true);
        }
    });

    MenuItem clear = new MenuItem("Clear");
    clear.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
    clear.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            vbox.setVisible(false);
        }
    });

    MenuItem exit = new MenuItem("Exit");
    exit.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            System.exit(0);
        }
    });

    menuFile.getItems().addAll(add, clear, new SeparatorMenuItem(), exit);

    // --- Menu Edit
    Menu menuEdit = new Menu("Edit");
    Menu menuEffect = new Menu("Picture Effect");

    final ToggleGroup groupEffect = new ToggleGroup();
    for (Entry effect : effects) {
        RadioMenuItem itemEffect = new RadioMenuItem((String) effect.getKey());
        itemEffect.setUserData(effect.getValue());
        itemEffect.setToggleGroup(groupEffect);
        menuEffect.getItems().add(itemEffect);
    }

    final MenuItem noEffects = new MenuItem("No Effects");
    noEffects.setDisable(true);
    noEffects.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            pic.setEffect(null);
            groupEffect.getSelectedToggle().setSelected(false);
            noEffects.setDisable(true);
        }
    });

    groupEffect.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
        public void changed(ObservableValue ov, Toggle old_toggle, Toggle new_toggle) {
            if (groupEffect.getSelectedToggle() != null) {
                Effect effect = (Effect) groupEffect.getSelectedToggle().getUserData();
                pic.setEffect(effect);
                noEffects.setDisable(false);
            } else {
                noEffects.setDisable(true);
            }
        }
    });

    menuEdit.getItems().addAll(menuEffect, noEffects);

    // --- Menu View
    Menu menuView = new Menu("View");
    CheckMenuItem titleView = createMenuItem("Title", name);
    CheckMenuItem binNameView = createMenuItem("Binomial name", binName);
    CheckMenuItem picView = createMenuItem("Picture", pic);
    CheckMenuItem descriptionView = createMenuItem("Decsription", description);

    menuView.getItems().addAll(titleView, binNameView, picView, descriptionView);
    menuBar.getMenus().addAll(menuFile, menuEdit, menuView);

    // --- Context Menu
    final ContextMenu cm = new ContextMenu();
    MenuItem cmItem1 = new MenuItem("Copy Image");
    cmItem1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            Clipboard clipboard = Clipboard.getSystemClipboard();
            ClipboardContent content = new ClipboardContent();
            content.putImage(pic.getImage());
            clipboard.setContent(content);
        }
    });

    cm.getItems().add(cmItem1);
    pic.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            if (e.getButton() == MouseButton.SECONDARY)
                cm.show(pic, e.getScreenX(), e.getScreenY());
        }
    });

    ((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);

    stage.setScene(scene);
    stage.show();
}