Example usage for javafx.scene.control MenuItem MenuItem

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

Introduction

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

Prototype

public MenuItem(String text) 

Source Link

Document

Constructs a MenuItem and sets the display text with the specified text

Usage

From source file:de.pixida.logtest.designer.MainWindow.java

private void createAndAppendHelpMenuItems(final Menu help) {
    final MenuItem visitDocumentation = new MenuItem("Visit Online Documentation");
    visitDocumentation.setGraphic(Icons.getIconGraphics("help"));
    visitDocumentation.setOnAction(event -> {
        Exception ex = null;//  ww w .  jav a  2 s.  co  m
        final String url = "https://github.com/Pixida/logtest/wiki";
        final Desktop desktop = java.awt.Desktop.getDesktop();
        if (desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
            try {
                desktop.browse(new URI(url));
            } catch (final Exception e) {
                ex = e;
            }
        } else {
            ex = new Exception("Browsing not supported.");
        }
        if (ex != null) {
            ExceptionDialog.showFatalException("Failed to open browser", "Visit us at " + url, ex);
        }
    });

    final MenuItem about = new MenuItem("About " + APP_TITLE);
    about.setGraphic(Icons.getIconGraphics(APP_ICON));
    about.setOnAction(event -> {
        final Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.initStyle(StageStyle.UTILITY);
        alert.setTitle(about.getText());
        alert.setHeaderText(APP_TITLE);
        alert.setContentText("Copyright (C) " + Calendar.getInstance().get(Calendar.YEAR) + " Pixida GmbH\n"
                + "\n" + "This application includes FAMFAMFAM icons (http://www.famfamfam.com).");
        alert.showAndWait();
    });

    help.getItems().addAll(visitDocumentation, about);
}

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//  w w  w .  ja  v  a  2  s .co m
        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);//w w w  .j  ava 2s . co  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:org.nmrfx.processor.gui.MainApp.java

MenuBar makeMenuBar(String appName) {
    MenuToolkit tk = null;//from ww w.j  ava2 s . com
    if (isMac()) {
        tk = MenuToolkit.toolkit();
    }
    MenuBar menuBar = new MenuBar();

    // Application Menu
    // TBD: services menu
    Menu appMenu = new Menu(appName); // Name for appMenu can't be set at
    // Runtime
    MenuItem aboutItem = null;
    Stage aboutStage = makeAbout(appName);
    if (tk != null) {
        aboutItem = tk.createAboutMenuItem(appName, aboutStage);
    } else {
        aboutItem = new MenuItem("About...");
        aboutItem.setOnAction(e -> aboutStage.show());
    }
    MenuItem prefsItem = new MenuItem("Preferences...");
    MenuItem quitItem;
    prefsItem.setOnAction(e -> showPreferences(e));
    if (tk != null) {
        quitItem = tk.createQuitMenuItem(appName);
        appMenu.getItems().addAll(aboutItem, new SeparatorMenuItem(), prefsItem, new SeparatorMenuItem(),
                tk.createHideMenuItem(appName), tk.createHideOthersMenuItem(), tk.createUnhideAllMenuItem(),
                new SeparatorMenuItem(), quitItem);
        // createQuitMeneItem doesn't result in stop or quit being called
        //  therefore we can't check for waiting till a commit is done before leaving
        // so explicitly set action to quit
        quitItem.setOnAction(e -> quit());
    } else {
        quitItem = new MenuItem("Quit");
        quitItem.setOnAction(e -> quit());
    }
    // File Menu (items TBD)
    Menu fileMenu = new Menu("File");
    MenuItem openMenuItem = new MenuItem("Open and Draw...");
    openMenuItem.setOnAction(e -> FXMLController.getActiveController().openAction(e));
    MenuItem addMenuItem = new MenuItem("Open...");
    addMenuItem.setOnAction(e -> FXMLController.getActiveController().addNoDrawAction(e));
    MenuItem newMenuItem = new MenuItem("New Window...");
    newMenuItem.setOnAction(e -> newGraphics(e));
    Menu recentMenuItem = new Menu("Open and Draw Recent");

    List<Path> recentDatasets = PreferencesController.getRecentDatasets();
    for (Path path : recentDatasets) {
        int count = path.getNameCount();
        int first = count - 3;
        first = first >= 0 ? first : 0;
        Path subPath = path.subpath(first, count);

        MenuItem datasetMenuItem = new MenuItem(subPath.toString());
        datasetMenuItem
                .setOnAction(e -> FXMLController.getActiveController().openFile(path.toString(), false, false));
        recentMenuItem.getItems().add(datasetMenuItem);
    }
    MenuItem pdfMenuItem = new MenuItem("Export PDF...");
    pdfMenuItem.setOnAction(e -> FXMLController.getActiveController().exportPDFAction(e));
    MenuItem svgMenuItem = new MenuItem("Export SVG...");
    svgMenuItem.setOnAction(e -> FXMLController.getActiveController().exportSVGAction(e));
    MenuItem loadPeakListMenuItem = new MenuItem("Load PeakLists");
    loadPeakListMenuItem.setOnAction(e -> loadPeakLists());

    Menu projectMenu = new Menu("Projects");

    MenuItem projectOpenMenuItem = new MenuItem("Open...");
    projectOpenMenuItem.setOnAction(e -> loadProject());

    MenuItem projectSaveAsMenuItem = new MenuItem("Save As...");
    projectSaveAsMenuItem.setOnAction(e -> saveProjectAs());

    MenuItem projectSaveMenuItem = new MenuItem("Save");
    projectSaveMenuItem.setOnAction(e -> saveProject());
    Menu recentProjectMenuItem = new Menu("Open Recent");

    List<Path> recentProjects = PreferencesController.getRecentProjects();
    for (Path path : recentProjects) {
        int count = path.getNameCount();
        int first = count - 3;
        first = first >= 0 ? first : 0;
        Path subPath = path.subpath(first, count);

        MenuItem projectMenuItem = new MenuItem(subPath.toString());
        projectMenuItem.setOnAction(e -> loadProject(path));
        recentProjectMenuItem.getItems().add(projectMenuItem);
    }

    projectMenu.getItems().addAll(projectOpenMenuItem, recentProjectMenuItem, projectSaveMenuItem,
            projectSaveAsMenuItem);

    fileMenu.getItems().addAll(openMenuItem, addMenuItem, newMenuItem, recentMenuItem, new SeparatorMenuItem(),
            pdfMenuItem, svgMenuItem, loadPeakListMenuItem);

    Menu spectraMenu = new Menu("Spectra");
    MenuItem deleteItem = new MenuItem("Delete Spectrum");
    deleteItem.setOnAction(e -> FXMLController.getActiveController().removeChart());
    MenuItem syncMenuItem = new MenuItem("Sync Axes");
    syncMenuItem.setOnAction(e -> PolyChart.activeChart.syncSceneMates());

    Menu arrangeMenu = new Menu("Arrange");
    MenuItem horizItem = new MenuItem("Horizontal");
    horizItem.setOnAction(
            e -> FXMLController.getActiveController().arrange(FractionPane.ORIENTATION.HORIZONTAL));
    MenuItem vertItem = new MenuItem("Vertical");
    vertItem.setOnAction(e -> FXMLController.getActiveController().arrange(FractionPane.ORIENTATION.VERTICAL));
    MenuItem gridItem = new MenuItem("Grid");
    gridItem.setOnAction(e -> FXMLController.getActiveController().arrange(FractionPane.ORIENTATION.GRID));
    MenuItem overlayItem = new MenuItem("Overlay");
    overlayItem.setOnAction(e -> FXMLController.getActiveController().overlay());
    MenuItem minimizeItem = new MenuItem("Minimize Borders");
    minimizeItem.setOnAction(e -> FXMLController.getActiveController().setBorderState(true));
    MenuItem normalizeItem = new MenuItem("Normal Borders");
    normalizeItem.setOnAction(e -> FXMLController.getActiveController().setBorderState(false));

    arrangeMenu.getItems().addAll(horizItem, vertItem, gridItem, overlayItem, minimizeItem, normalizeItem);
    MenuItem alignMenuItem = new MenuItem("Align Spectra");
    alignMenuItem.setOnAction(e -> FXMLController.getActiveController().alignCenters());
    MenuItem analyzeMenuItem = new MenuItem("Analyzer...");
    analyzeMenuItem.setOnAction(e -> showAnalyzer(e));

    spectraMenu.getItems().addAll(deleteItem, arrangeMenu, syncMenuItem, alignMenuItem, analyzeMenuItem);

    // Format (items TBD)
    //        Menu formatMenu = new Menu("Format");
    //        formatMenu.getItems().addAll(new MenuItem("TBD"));
    // View Menu (items TBD)
    Menu viewMenu = new Menu("View");
    MenuItem dataMenuItem = new MenuItem("Show Datasets");
    dataMenuItem.setOnAction(e -> showDatasetsTable(e));

    MenuItem consoleMenuItem = new MenuItem("Show Console");
    consoleMenuItem.setOnAction(e -> showConsole(e));

    MenuItem attrMenuItem = new MenuItem("Show Attributes");
    attrMenuItem.setOnAction(e -> FXMLController.getActiveController().showSpecAttrAction(e));

    MenuItem procMenuItem = new MenuItem("Show Processor");
    procMenuItem.setOnAction(e -> FXMLController.getActiveController().showProcessorAction(e));

    MenuItem scannerMenuItem = new MenuItem("Show Scanner");
    scannerMenuItem.setOnAction(e -> FXMLController.getActiveController().showScannerAction(e));

    viewMenu.getItems().addAll(consoleMenuItem, dataMenuItem, attrMenuItem, procMenuItem, scannerMenuItem);

    Menu peakMenu = new Menu("Peaks");

    MenuItem peakAttrMenuItem = new MenuItem("Show Peak Tool");
    peakAttrMenuItem.setOnAction(e -> FXMLController.getActiveController().showPeakAttrAction(e));

    MenuItem peakNavigatorMenuItem = new MenuItem("Show Peak Navigator");
    peakNavigatorMenuItem.setOnAction(e -> FXMLController.getActiveController().showPeakNavigator());

    MenuItem linkPeakDimsMenuItem = new MenuItem("Link by Labels");
    linkPeakDimsMenuItem.setOnAction(e -> FXMLController.getActiveController().linkPeakDims());

    MenuItem peakSliderMenuItem = new MenuItem("Show Peak Slider");
    peakSliderMenuItem.setOnAction(e -> FXMLController.getActiveController().showPeakSlider());

    peakMenu.getItems().addAll(peakAttrMenuItem, peakNavigatorMenuItem, linkPeakDimsMenuItem,
            peakSliderMenuItem);

    // Window Menu
    // TBD standard window menu items
    // Help Menu (items TBD)
    Menu helpMenu = new Menu("Help");

    MenuItem webSiteMenuItem = new MenuItem("NMRFx Web Site");
    webSiteMenuItem.setOnAction(e -> showWebSiteAction(e));

    MenuItem docsMenuItem = new MenuItem("Online Documentation");
    docsMenuItem.setOnAction(e -> showDocAction(e));

    MenuItem versionMenuItem = new MenuItem("Check Version");
    versionMenuItem.setOnAction(e -> showVersionAction(e));

    MenuItem mailingListItem = new MenuItem("Mailing List Site");
    mailingListItem.setOnAction(e -> showMailingListAction(e));

    MenuItem refMenuItem = new MenuItem("NMRFx Publication");
    refMenuItem.setOnAction(e -> {
        MainApp.hostServices.showDocument("http://link.springer.com/article/10.1007/s10858-016-0049-6");
    });

    // home
    // mailing list
    //
    helpMenu.getItems().addAll(docsMenuItem, webSiteMenuItem, mailingListItem, versionMenuItem, refMenuItem);

    if (tk != null) {
        Menu windowMenu = new Menu("Window");
        windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(),
                tk.createCycleWindowsItem(), new SeparatorMenuItem(), tk.createBringAllToFrontItem());
        menuBar.getMenus().addAll(appMenu, fileMenu, projectMenu, spectraMenu, viewMenu, peakMenu, windowMenu,
                helpMenu);
        tk.autoAddWindowMenuItems(windowMenu);
        tk.setGlobalMenuBar(menuBar);
    } else {
        fileMenu.getItems().add(prefsItem);
        fileMenu.getItems().add(quitItem);
        menuBar.getMenus().addAll(fileMenu, projectMenu, spectraMenu, viewMenu, peakMenu, helpMenu);
        helpMenu.getItems().add(0, aboutItem);
    }
    return menuBar;
}

From source file:de.ks.idnadrev.information.chart.ChartDataEditor.java

protected void onColumnsChanged(ListChangeListener.Change<? extends SimpleStringProperty> c) {
    while (c.next()) {
        List<? extends SimpleStringProperty> added = c.getAddedSubList();
        List<? extends SimpleStringProperty> removed = c.getRemoved();

        for (SimpleStringProperty column : added) {
            int columnIndex = columnHeaders.indexOf(column);
            addColumnConstraint();/*from  w w w  .  j  a va2s  .  c o m*/

            TextField title = new TextField();
            title.textProperty().bindBidirectional(column);
            title.getStyleClass().add("editorViewLabel");

            MenuItem deleteColumnItem = new MenuItem(Localized.get("column.delete"));
            deleteColumnItem.setOnAction(e -> {
                columnHeaders.remove(column);
            });
            title.setContextMenu(new ContextMenu(deleteColumnItem));

            headers.add(title);
            dataContainer.add(title, columnIndex + COLUMN_OFFSET, 0);

            for (int i = 0; i < rows.size(); i++) {
                ChartRow chartRow = rows.get(i);
                SimpleStringProperty value = chartRow.getValue(columnIndex);

                TextField editor = createValueEditor(chartRow, i, columnIndex);
                editor.textProperty().bindBidirectional(value);
            }
        }
        for (SimpleStringProperty column : removed) {
            Optional<Integer> first = dataContainer.getChildren().stream()
                    .filter(n -> GridPane.getRowIndex(n) == 0).map(n -> (TextField) n)
                    .filter(t -> t.getText().equals(column.getValue())).map(t -> GridPane.getColumnIndex(t))
                    .findFirst();
            if (first.isPresent()) {
                int columnIndex = first.get();
                rows.forEach(r -> {
                    SimpleStringProperty value = r.getValue(columnIndex);
                    value.set("");
                    value.unbind();
                });
                List<Node> childrenToRemove = dataContainer.getChildren().stream()
                        .filter(n -> GridPane.getColumnIndex(n) == columnIndex).collect(Collectors.toList());
                dataContainer.getChildren().removeAll(childrenToRemove);
                dataContainer.getColumnConstraints().remove(dataContainer.getColumnConstraints().size() - 1);
            }
        }

        sortGridPane();
    }
}

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

/**
 * descriptionReader is optional//www  .  ja  va  2s. c o m
 */
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:de.pixida.logtest.designer.MainWindow.java

private void createAndAppendFileMenuItems(final Menu menu) {
    final Menu newDocument = new Menu("New");
    final Menu open = new Menu("Open");
    for (final Type type : Editor.Type.values()) {
        final MenuItem newFile = new MenuItem(type.getName());
        newFile.setOnAction(event -> this.handleCreateNewDocument(type));
        newDocument.getItems().add(newFile);

        if (type.supportsFilesProperty().get()) {
            final MenuItem openFile = new MenuItem(type.getName());
            openFile.setOnAction(event -> {
                final FileChooser fileChooser = this.createFileDialog(type, "Open");
                final File selectedFile = fileChooser.showOpenDialog(this.primaryStage);
                if (selectedFile != null) {
                    this.applyFolderOfSelectedFileInOpenOrSaveAsFileDialog(selectedFile);
                    this.handleLoadDocument(type, selectedFile);
                }//from w w w. ja  va  2s. c om
            });
            open.getItems().add(openFile);
        }
    }

    this.menuItemSave = new MenuItem("Save");
    this.menuItemSave.setGraphic(Icons.getIconGraphics("disk"));
    this.menuItemSave.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN));
    this.menuItemSave.setOnAction(event -> this.handleSaveDocument());

    this.menuItemSaveAs = new MenuItem("Save as");
    this.menuItemSaveAs.setOnAction(event -> this.handleSaveDocumentAs());

    final MenuItem exit = new MenuItem("Exit");
    exit.setOnAction(event -> this.handleExitApplication());

    menu.getItems().addAll(newDocument, open, this.menuItemSave, this.menuItemSaveAs, new SeparatorMenuItem(),
            exit);
}

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

/**
 * Creates the context menu.//from   w w w  .j  a va 2s  . com
 *
 * @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 -> {/*w w w. ja  v  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:org.pdfsam.ui.selection.multiple.SelectionTable.java

private MenuItem createMenuItem(String text, AwesomeIcon icon) {
    MenuItem item = new MenuItem(text);
    AwesomeDude.setIcon(item, icon);/*from  w  w w  . j a  va2 s.  c o  m*/
    item.setDisable(true);
    return item;
}