Example usage for javafx.scene.control MenuItem setOnAction

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

Introduction

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

Prototype

public final void setOnAction(EventHandler<ActionEvent> value) 

Source Link

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;/*from w  w w  . j  av a  2s  .  c o  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. j  a  v  a 2s .c  om*/
        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:calendarioSeries.vistas.MainViewController.java

public void populateImagenes() {
    Platform.runLater(new Runnable() {
        @Override//from   w ww . j a  v  a 2s  .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:gov.va.isaac.gui.ConceptNode.java

/**
 * descriptionReader is optional// w w w. j  a v a 2s . 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: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 www. ja va2  s .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:jp.ac.tohoku.ecei.sb.metabolome.lims.gui.MainWindowController.java

@Override
public void initialize(URL location, ResourceBundle resources) {
    // Table Study
    initializeTable(tableStudy, StudyImpl.class);
    initializeTable(tablePlate, PlateImpl.class);
    initializeTable(tableSample, SampleImpl.class);
    initializeTable(tableInjection, InjectionImpl.class);
    initializeTable(tableCompound, CompoundImpl.class);
    initializeTable(tableHistory, OperationHistoryImpl.class);

    menuBar.setUseSystemMenuBar(true);//w  w  w. ja  v  a 2s.  co m

    commandManager = new CommandManager();
    commandManager.setContext(commandManagerContext);
    final GUICommandPaneFactory commandPaneFactory = new GUICommandPaneFactory(commandManager);
    MetabolomeQC.addCorrectionCommands(commandManager);
    for (Map.Entry<String, Class> commend : commandManager.getCommands().entrySet()) {
        MenuItem menuItem = new MenuItem(commend.getKey());
        menuItem.setText(commend.getKey());
        menuItem.setOnAction(e -> {
            final Stage stage = new Stage();
            stage.initModality(Modality.WINDOW_MODAL);

            Parent guiCommand = commandPaneFactory.getCommandPane(commend.getKey(),
                    (commandEvent, managedCommand) -> {
                        stage.close();
                    });
            BorderPane margins = new BorderPane(guiCommand);
            BorderPane.setMargin(guiCommand, new Insets(10));

            stage.setScene(new Scene(margins));
            stage.initOwner(this.stage);
            stage.showAndWait();
            onRefresh(null);
        });
        correctionMenu.getItems().add(menuItem);
    }

    onRefresh(null);
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private MenuItem createAddMenu(String name, TreeView<Object> elements, TreeItem<Object> selected) {
    ListHolder listHolder = (ListHolder) selected.getValue();

    MenuItem add = new MenuItem(name);
    add.setOnAction(event -> {
        Stream<ClassHolder> st = SubclassManager.getInstance().getClassWithAllSubclasses(listHolder.type)
                .stream().map(ClassHolder::new);
        List<ClassHolder> list = st.collect(Collectors.toList());

        Optional<ClassHolder> choice;

        if (list.size() == 1) {
            choice = Optional.of(list.get(0));
        } else {/*w  w  w  .  j  ava 2  s .co  m*/
            ChoiceDialog<ClassHolder> cd = new ChoiceDialog<>(list.get(0), list);
            cd.setTitle("Select class");
            cd.setHeaderText(null);
            choice = cd.showAndWait();
        }
        choice.ifPresent(toCreate -> {
            try {
                IOEntity obj = toCreate.clazz.newInstance();

                listHolder.list.add(obj);
                TreeItem<Object> treeItem = createTreeItem(obj);
                selected.getChildren().add(treeItem);
                elements.getSelectionModel().select(treeItem);
                elements.scrollTo(elements.getSelectionModel().getSelectedIndex());

                editor.getHistory().valueCreated(treeItemToScriptString(selected), toCreate.clazz);
            } catch (ReflectiveOperationException e) {
                log.log(Level.WARNING, String.format("Couldn't instantiate %s", toCreate.clazz.getName()), e);
                Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                        "Couldn't instantiate " + toCreate.clazz);
            }
        });
    });

    return add;
}

From source file:pl.baczkowicz.mqttspy.ui.NewPublicationController.java

/**
 * Refreshes the list of recent messages shown in the publish button's context menu.
 *///  w w w . j  a  v a2 s.  c  om
private void refreshRecentMessages() {
    // Remove all elements
    while (recentMessagesMenu.getItems().size() > 0) {
        recentMessagesMenu.getItems().remove(0);
    }
    while (saveRecentMessagesMenu.getItems().size() > 0) {
        saveRecentMessagesMenu.getItems().remove(0);
    }

    // Add all elements
    for (final ReceivedMqttMessage message : recentMessages) {
        final String topic = message.getTopic();
        final String payload = message.getPayload().length() > 10
                ? message.getPayload().substring(0, 10) + "..."
                : message.getPayload();
        final String time = TimeUtils.DATE_WITH_SECONDS_SDF.format(message.getDate());

        final String messageText = "Topic = '" + topic + "', payload = '" + payload + "', published at " + time;
        final MenuItem recentMessageItem = new MenuItem(messageText);
        recentMessageItem.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                displayMessage(message);
            }
        });
        recentMessagesMenu.getItems().add(recentMessageItem);

        final MenuItem saveMessageItem = new MenuItem(messageText);
        saveMessageItem.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                saveAsScript(message);
            }
        });
        saveRecentMessagesMenu.getItems().add(saveMessageItem);
    }

    recentMessagesMenu.setDisable(recentMessagesMenu.getItems().size() == 0);
    saveRecentMessagesMenu.setDisable(saveRecentMessagesMenu.getItems().size() == 0);
}

From source file:se.trixon.filebydate.ui.MainApp.java

private void initMac() {
    MenuToolkit menuToolkit = MenuToolkit.toolkit();
    Menu applicationMenu = menuToolkit.createDefaultApplicationMenu(APP_TITLE);
    menuToolkit.setApplicationMenu(applicationMenu);

    applicationMenu.getItems().remove(0);
    MenuItem aboutMenuItem = new MenuItem(String.format(Dict.ABOUT_S.toString(), APP_TITLE));
    aboutMenuItem.setOnAction(mAboutAction);

    MenuItem settingsMenuItem = new MenuItem(Dict.PREFERENCES.toString());
    settingsMenuItem.setOnAction(mOptionsAction);
    settingsMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.COMMA, KeyCombination.SHORTCUT_DOWN));

    applicationMenu.getItems().add(0, aboutMenuItem);
    applicationMenu.getItems().add(2, settingsMenuItem);

    int cnt = applicationMenu.getItems().size();
    applicationMenu.getItems().get(cnt - 1).setText(String.format("%s %s", Dict.QUIT.toString(), APP_TITLE));
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private void updateContextMenu(ContextMenu contextMenu, TreeView<Object> elements) {
    contextMenu.getItems().clear();//  w w w .  ja  v  a2 s .  c  om

    TreeItem<Object> root = elements.getRoot();
    TreeItem<Object> selected = elements.getSelectionModel().getSelectedItem();

    if (selected == null) {
        if (root != null)
            contextMenu.getItems().add(createAddMenu("Add ..", elements, root));
    } else {
        Object value = selected.getValue();
        if (value instanceof ListHolder) {
            contextMenu.getItems().add(createAddMenu("Add ..", elements, selected));
        } else if (selected.getParent() != null && selected.getParent().getValue() instanceof ListHolder) {
            MenuItem add = createAddMenu("Add to parent ..", elements, selected.getParent());

            MenuItem delete = new MenuItem("Delete");
            delete.setOnAction(event -> {
                ListHolder parent = (ListHolder) selected.getParent().getValue();

                int index = parent.list.indexOf(value);
                editor.getHistory().valueRemoved(treeItemToScriptString(selected.getParent()), index);

                parent.list.remove(index);
                selected.getParent().getChildren().remove(selected);

                elements.getSelectionModel().selectPrevious();
                elements.getSelectionModel().selectNext();
            });
            contextMenu.getItems().addAll(add, delete);
        }
        if (value instanceof ComponentFactory) {
            MenuItem view = new MenuItem("View");
            view.setOnAction(event -> {
                if (value instanceof L2Context)
                    ((L2Context) value).setResources(l2resources.getValue());
                Stage stage = new Stage();
                stage.setTitle(value.toString());
                Scene scene = new Scene(((ComponentFactory) value).getComponent());
                scene.getStylesheets().add(getClass().getResource("l2.css").toExternalForm());
                stage.setScene(scene);
                stage.show();
            });
            contextMenu.getItems().add(view);
        }
    }
}