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(MenuItem... items) 

Source Link

Document

Create a new ContextMenu initialized with the given items

Usage

From source file:com.properned.application.LocaleListCell.java

@Override
protected void updateItem(Locale locale, boolean empty) {
    super.updateItem(locale, empty);
    setGraphic(null);/*from   www . j  av  a 2 s.  co m*/
    setText(null);
    if (locale != null) {
        String localeToString = locale.toString();
        if (localeToString.isEmpty()) {
            localeToString = MessageReader.getInstance().getMessage("locale.default");
        }
        if (StringUtils.isNotEmpty(locale.getDisplayName())) {
            localeToString += " (" + locale.getDisplayName() + ")";
        }

        setText(localeToString);

        MenuItem deleteMenu = getDeleteMenu(locale);
        this.setContextMenu(new ContextMenu(deleteMenu));

    }
}

From source file:Main.java

@Override
public void start(Stage primaryStage) {
    BorderPane root = new BorderPane();
    Scene scene = new Scene(root, 300, 250, Color.WHITE);
    MenuBar menuBar = new MenuBar();
    menuBar.getMenus().addAll(fileMenu(), cameraMenu(), alarmMenu());
    root.setTop(menuBar);//from w  w w  .  ja  va 2s .  c o m
    ContextMenu contextFileMenu = new ContextMenu(exitMenuItem());

    primaryStage.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent me) -> {
        if (me.getButton() == MouseButton.SECONDARY || me.isControlDown()) {
            contextFileMenu.show(root, me.getScreenX(), me.getScreenY());
        } else {
            contextFileMenu.hide();
        }
    });
    primaryStage.setScene(scene);
    primaryStage.show();
}

From source file:Watcher.FXMLDocumentController.java

@Override
public void initialize(URL url, ResourceBundle rb) {
    ServiceHandler.start(new notificationService());

    try {/*from w  w w  .  j  a  v  a 2  s  .  c  om*/
        HSQL_Manager.init("jdbc:hsqldb:file:src/dbEnv/", "SA", "");
    } catch (ClassNotFoundException | SQLException ex) {
        Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
    }

    int count = 0;
    for (Site a : HSQL_Manager.getSites()) {
        items.add(a.getAddress());

        try {
            //sites.add(new Site(siteList.getItems().get(i).toString()));
            watcherManager.addSite(a);
        } catch (WatchDogNotStartedException | SiteAlreadyAddedException ex) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            new errDialog().showError(sw.toString());
            break;
        }
        count++;
    }

    MenuItem deleteItem = new MenuItem("Delete");
    final ContextMenu contextMenu = new ContextMenu(deleteItem);
    contextMenu.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent t) {
            removeItem(new Site(siteList.getSelectionModel().getSelectedItem().toString()));
        }
    });
    siteList.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {

        @Override
        public ListCell<String> call(ListView<String> param) {
            ListCell<String> cell = new ListCell<String>() {

                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    //textProperty().unbind();
                    setContextMenu(null);
                    if (!empty && item != null) {
                        setContextMenu(contextMenu);
                        setText(item);
                    }
                    if (item != null) {
                    } else {
                        setGraphic(null);
                        setText("");
                    }
                }
            };
            return cell;
        }
    });

    siteList.getSelectionModel().selectedItemProperty().addListener(new listViewChangeListener());
    siteList.setItems(items);
    siteList.autosize();

    if (count > 0) {
        siteList.getSelectionModel().select(0);
    }
    uptime.setAnimated(false);
    //uptime.setStyle(null);
    processor = new processData(uptime, detailedData);

    try {
        ServiceHandler.startService(new InternetWatcher("http://www.google.com", 3));
        ServiceHandler.startService(
                new StatusUpdater(1, (FXMLDocumentController) JavaFXApplication4.getLoader().getController()));
    } catch (InternetWatcherServiceAlreadyStartedException | WatchDogTimerServiceAlreadyStartedException
            | StatusUpdaterServiceAlreadyStartedException ex) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        new errDialog().showError(sw.toString());
    }

    removeFilter.setOnMousePressed(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent t) {
            if (t.isPrimaryButtonDown()) {
                processor.cancelFilter(getSelectedItem());
            }
        }
    });
}

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();//w  ww.  j  av a  2 s.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:org.sleuthkit.autopsy.imagegallery.gui.GroupPane.java

/**
 * called automatically during constructor by FXMLConstructor.
 *
 * checks that FXML loading went ok and performs additional setup
 *//*from  w  w  w  .j  a  va2 s.  c o  m*/
@FXML
void initialize() {
    assert gridView != null : "fx:id=\"tilePane\" was not injected: check your FXML file 'GroupPane.fxml'.";
    assert grpCatSplitMenu != null : "fx:id=\"grpCatSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert grpTagSplitMenu != null : "fx:id=\"grpTagSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert headerToolBar != null : "fx:id=\"headerToolBar\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert segButton != null : "fx:id=\"previewList\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert slideShowToggle != null : "fx:id=\"segButton\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert tileToggle != null : "fx:id=\"tileToggle\" was not injected: check your FXML file 'GroupHeader.fxml'.";

    //configure flashing glow animation on next unseen group button
    flashAnimation.setCycleCount(Timeline.INDEFINITE);
    flashAnimation.setAutoReverse(true);

    //configure gridView cell properties
    gridView.cellHeightProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75));
    gridView.cellWidthProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75));
    gridView.setCellFactory((GridView<Long> param) -> new DrawableCell());

    //configure toolbar properties
    HBox.setHgrow(spacer, Priority.ALWAYS);
    spacer.setMinWidth(Region.USE_PREF_SIZE);

    try {
        grpTagSplitMenu.setText(TagUtils.getFollowUpTagName().getDisplayName());
        grpTagSplitMenu.setOnAction(createGrpTagMenuItem(TagUtils.getFollowUpTagName()).getOnAction());
    } catch (TskCoreException tskCoreException) {
        LOGGER.log(Level.WARNING, "failed to load FollowUpTagName", tskCoreException);
    }
    grpTagSplitMenu.setGraphic(new ImageView(DrawableAttribute.TAGS.getIcon()));
    grpTagSplitMenu.showingProperty()
            .addListener((ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) -> {
                if (t1) {
                    ArrayList<MenuItem> selTagMenues = new ArrayList<>();
                    for (final TagName tn : TagUtils.getNonCategoryTagNames()) {
                        MenuItem menuItem = TagUtils.createSelTagMenuItem(tn, grpTagSplitMenu);
                        selTagMenues.add(menuItem);
                    }
                    grpTagSplitMenu.getItems().setAll(selTagMenues);
                }
            });

    ArrayList<MenuItem> grpCategoryMenues = new ArrayList<>();
    for (final Category cat : Category.values()) {
        MenuItem menuItem = createGrpCatMenuItem(cat);
        grpCategoryMenues.add(menuItem);
    }
    grpCatSplitMenu.setText(Category.FIVE.getDisplayName());
    grpCatSplitMenu.setGraphic(new ImageView(DrawableAttribute.CATEGORY.getIcon()));
    grpCatSplitMenu.getItems().setAll(grpCategoryMenues);
    grpCatSplitMenu.setOnAction(createGrpCatMenuItem(Category.FIVE).getOnAction());

    Runnable syncMode = () -> {
        switch (groupViewMode.get()) {
        case SLIDE_SHOW:
            slideShowToggle.setSelected(true);
            break;
        case TILE:
            tileToggle.setSelected(true);
            break;
        }
    };
    syncMode.run();
    //make togle states match view state
    groupViewMode.addListener((o) -> {
        syncMode.run();
    });

    slideShowToggle.toggleGroupProperty().addListener((o) -> {
        slideShowToggle.getToggleGroup().selectedToggleProperty()
                .addListener((observable, oldToggle, newToggle) -> {
                    if (newToggle == null) {
                        oldToggle.setSelected(true);
                    }
                });
    });

    //listen to toggles and update view state
    slideShowToggle.setOnAction((ActionEvent t) -> {
        activateSlideShowViewer(globalSelectionModel.lastSelectedProperty().get());
    });

    tileToggle.setOnAction((ActionEvent t) -> {
        activateTileViewer();
    });

    controller.viewState().addListener((ObservableValue<? extends GroupViewState> observable,
            GroupViewState oldValue, GroupViewState newValue) -> {
        setViewState(newValue);
    });

    addEventFilter(KeyEvent.KEY_PRESSED, tileKeyboardNavigationHandler);
    gridView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

        private ContextMenu buildContextMenu() {
            ArrayList<MenuItem> menuItems = new ArrayList<>();

            menuItems.add(CategorizeAction.getPopupMenu());

            menuItems.add(AddDrawableTagAction.getInstance().getPopupMenu());

            Collection<? extends ContextMenuActionsProvider> menuProviders = Lookup.getDefault()
                    .lookupAll(ContextMenuActionsProvider.class);

            for (ContextMenuActionsProvider provider : menuProviders) {

                for (final Action act : provider.getActions()) {

                    if (act instanceof Presenter.Popup) {
                        Presenter.Popup aact = (Presenter.Popup) act;

                        menuItems.add(SwingMenuItemAdapter.create(aact.getPopupPresenter()));
                    }
                }
            }
            final MenuItem extractMenuItem = new MenuItem("Extract File(s)");
            extractMenuItem.setOnAction((ActionEvent t) -> {
                SwingUtilities.invokeLater(() -> {
                    TopComponent etc = WindowManager.getDefault()
                            .findTopComponent(ImageGalleryTopComponent.PREFERRED_ID);
                    ExtractAction.getInstance().actionPerformed(new java.awt.event.ActionEvent(etc, 0, null));
                });
            });
            menuItems.add(extractMenuItem);

            ContextMenu contextMenu = new ContextMenu(menuItems.toArray(new MenuItem[] {}));
            contextMenu.setAutoHide(true);
            return contextMenu;
        }

        @Override
        public void handle(MouseEvent t) {
            switch (t.getButton()) {
            case PRIMARY:
                if (t.getClickCount() == 1) {
                    globalSelectionModel.clearSelection();
                    if (contextMenu != null) {
                        contextMenu.hide();
                    }
                }
                t.consume();
                break;
            case SECONDARY:
                if (t.getClickCount() == 1) {
                    selectAllFiles();
                }
                if (globalSelectionModel.getSelected().isEmpty() == false) {
                    if (contextMenu == null) {
                        contextMenu = buildContextMenu();
                    }

                    contextMenu.hide();
                    contextMenu.show(GroupPane.this, t.getScreenX(), t.getScreenY());
                }
                t.consume();
                break;
            }
        }
    });

    ActionUtils.configureButton(nextGroupAction, nextButton);
    final EventHandler<ActionEvent> onAction = nextButton.getOnAction();
    nextButton.setOnAction((ActionEvent event) -> {
        flashAnimation.stop();
        nextButton.setEffect(null);
        onAction.handle(event);
    });

    ActionUtils.configureButton(forwardAction, forwardButton);
    ActionUtils.configureButton(backAction, backButton);

    nextGroupAction.disabledProperty().addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
                nextButton.setEffect(newValue ? null : DROP_SHADOW);
                if (newValue == false) {
                    flashAnimation.play();
                } else {
                    flashAnimation.stop();
                }
            });

    //listen to tile selection and make sure it is visible in scroll area
    //TODO: make sure we are testing complete visability not just bounds intersection
    globalSelectionModel.lastSelectedProperty().addListener((observable, oldFileID, newFileId) -> {
        if (groupViewMode.get() == GroupViewMode.SLIDE_SHOW) {
            slideShowPane.setFile(newFileId);
        } else {

            scrollToFileID(newFileId);
        }
    });

    setViewState(controller.viewState().get());
}

From source file:org.sleuthkit.autopsy.imageanalyzer.gui.GroupPane.java

/**
 * called automatically during constructor by FXMLConstructor.
 *
 * checks that FXML loading went ok and performs additional setup
 *//*  w w  w.ja  v  a 2 s.c  o m*/
@FXML
void initialize() {
    assert gridView != null : "fx:id=\"tilePane\" was not injected: check your FXML file 'GroupPane.fxml'.";
    assert grpCatSplitMenu != null : "fx:id=\"grpCatSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert grpTagSplitMenu != null : "fx:id=\"grpTagSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert headerToolBar != null : "fx:id=\"headerToolBar\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert segButton != null : "fx:id=\"previewList\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert slideShowToggle != null : "fx:id=\"segButton\" was not injected: check your FXML file 'GroupHeader.fxml'.";
    assert tileToggle != null : "fx:id=\"tileToggle\" was not injected: check your FXML file 'GroupHeader.fxml'.";

    grouping.addListener(new InvalidationListener() {
        private void updateFiles() {
            final ObservableList<Long> fileIds = grouping.get().fileIds();
            Platform.runLater(() -> {
                gridView.setItems(FXCollections.observableArrayList(fileIds));
            });
            resetHeaderString();
        }

        @Override
        public void invalidated(Observable o) {
            getScrollBar().ifPresent((scrollBar) -> {
                scrollBar.setValue(0);
            });

            //set the embeded header
            resetHeaderString();
            //and assign fileIDs to gridView
            if (grouping.get() == null) {
                Platform.runLater(gridView.getItems()::clear);

            } else {
                grouping.get().fileIds().addListener((Observable observable) -> {
                    updateFiles();
                });

                updateFiles();
            }
        }
    });

    //configure flashing glow animation on next unseen group button
    flashAnimation.setCycleCount(Timeline.INDEFINITE);
    flashAnimation.setAutoReverse(true);

    //configure gridView cell properties
    gridView.cellHeightProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75));
    gridView.cellWidthProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75));
    gridView.setCellFactory((GridView<Long> param) -> new DrawableCell());

    //configure toolbar properties
    HBox.setHgrow(spacer, Priority.ALWAYS);
    spacer.setMinWidth(Region.USE_PREF_SIZE);

    ArrayList<MenuItem> grpTagMenues = new ArrayList<>();
    for (final TagName tn : TagUtils.getNonCategoryTagNames()) {
        MenuItem menuItem = createGrpTagMenuItem(tn);
        grpTagMenues.add(menuItem);
    }
    try {
        grpTagSplitMenu.setText(TagUtils.getFollowUpTagName().getDisplayName());
        grpTagSplitMenu.setOnAction(createGrpTagMenuItem(TagUtils.getFollowUpTagName()).getOnAction());
    } catch (TskCoreException tskCoreException) {
        LOGGER.log(Level.WARNING, "failed to load FollowUpTagName", tskCoreException);
    }
    grpTagSplitMenu.setGraphic(new ImageView(DrawableAttribute.TAGS.getIcon()));
    grpTagSplitMenu.getItems().setAll(grpTagMenues);

    ArrayList<MenuItem> grpCategoryMenues = new ArrayList<>();
    for (final Category cat : Category.values()) {
        MenuItem menuItem = createGrpCatMenuItem(cat);
        grpCategoryMenues.add(menuItem);
    }
    grpCatSplitMenu.setText(Category.FIVE.getDisplayName());
    grpCatSplitMenu.setGraphic(new ImageView(DrawableAttribute.CATEGORY.getIcon()));
    grpCatSplitMenu.getItems().setAll(grpCategoryMenues);
    grpCatSplitMenu.setOnAction(createGrpCatMenuItem(Category.FIVE).getOnAction());

    Runnable syncMode = () -> {
        switch (groupViewMode.get()) {
        case SLIDE_SHOW:
            slideShowToggle.setSelected(true);
            break;
        case TILE:
            tileToggle.setSelected(true);
            break;
        }
    };
    syncMode.run();
    //make togle states match view state
    groupViewMode.addListener((o) -> {
        syncMode.run();
    });

    slideShowToggle.toggleGroupProperty().addListener((o) -> {
        slideShowToggle.getToggleGroup().selectedToggleProperty()
                .addListener((observable, oldToggle, newToggle) -> {
                    if (newToggle == null) {
                        oldToggle.setSelected(true);
                    }
                });
    });

    //listen to toggles and update view state
    slideShowToggle.setOnAction((ActionEvent t) -> {
        activateSlideShowViewer(globalSelectionModel.lastSelectedProperty().get());
    });

    tileToggle.setOnAction((ActionEvent t) -> {
        activateTileViewer();
    });

    controller.viewState().addListener((ObservableValue<? extends GroupViewState> observable,
            GroupViewState oldValue, GroupViewState newValue) -> {
        setViewState(newValue);
    });

    addEventFilter(KeyEvent.KEY_PRESSED, tileKeyboardNavigationHandler);
    gridView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

        private ContextMenu buildContextMenu() {
            ArrayList<MenuItem> menuItems = new ArrayList<>();

            menuItems.add(CategorizeAction.getPopupMenu());

            menuItems.add(AddDrawableTagAction.getInstance().getPopupMenu());

            Collection<? extends ContextMenuActionsProvider> menuProviders = Lookup.getDefault()
                    .lookupAll(ContextMenuActionsProvider.class);

            for (ContextMenuActionsProvider provider : menuProviders) {

                for (final Action act : provider.getActions()) {

                    if (act instanceof Presenter.Popup) {
                        Presenter.Popup aact = (Presenter.Popup) act;

                        menuItems.add(SwingMenuItemAdapter.create(aact.getPopupPresenter()));
                    }
                }
            }
            final MenuItem extractMenuItem = new MenuItem("Extract File(s)");
            extractMenuItem.setOnAction((ActionEvent t) -> {
                SwingUtilities.invokeLater(() -> {
                    TopComponent etc = WindowManager.getDefault()
                            .findTopComponent(ImageAnalyzerTopComponent.PREFERRED_ID);
                    ExtractAction.getInstance().actionPerformed(new java.awt.event.ActionEvent(etc, 0, null));
                });
            });
            menuItems.add(extractMenuItem);

            ContextMenu contextMenu = new ContextMenu(menuItems.toArray(new MenuItem[] {}));
            contextMenu.setAutoHide(true);
            return contextMenu;
        }

        @Override
        public void handle(MouseEvent t) {
            switch (t.getButton()) {
            case PRIMARY:
                if (t.getClickCount() == 1) {
                    globalSelectionModel.clearSelection();
                    if (contextMenu != null) {
                        contextMenu.hide();
                    }
                }
                t.consume();
                break;
            case SECONDARY:
                if (t.getClickCount() == 1) {
                    selectAllFiles();
                }
                if (contextMenu == null) {
                    contextMenu = buildContextMenu();
                }

                contextMenu.hide();
                contextMenu.show(GroupPane.this, t.getScreenX(), t.getScreenY());
                t.consume();
                break;
            }
        }
    });

    //        Platform.runLater(() -> {
    ActionUtils.configureButton(nextGroupAction, nextButton);
    final EventHandler<ActionEvent> onAction = nextButton.getOnAction();
    nextButton.setOnAction((ActionEvent event) -> {
        flashAnimation.stop();
        nextButton.setEffect(null);
        onAction.handle(event);
    });

    ActionUtils.configureButton(forwardAction, forwardButton);
    ActionUtils.configureButton(backAction, backButton);
    //        });

    nextGroupAction.disabledProperty().addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
                nextButton.setEffect(newValue ? null : DROP_SHADOW);
                if (newValue == false) {
                    flashAnimation.play();
                } else {
                    flashAnimation.stop();
                }
            });

    //listen to tile selection and make sure it is visible in scroll area
    //TODO: make sure we are testing complete visability not just bounds intersection
    globalSelectionModel.lastSelectedProperty().addListener((observable, oldFileID, newFileId) -> {
        if (groupViewMode.get() == GroupViewMode.SLIDE_SHOW) {
            slideShowPane.setFile(newFileId);
        } else {

            scrollToFileID(newFileId);
        }
    });

    setViewState(controller.viewState().get());
}