Example usage for javafx.scene.control ContextMenu setOnAction

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

Introduction

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

Prototype

public final void setOnAction(EventHandler<ActionEvent> value) 

Source Link

Usage

From source file:Main.java

@Override
public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    TextField notification = new TextField();

    MenuItem item1 = new MenuItem("About");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("About");
        }//from  www  . j  a v a 2 s  .c  o  m
    });
    MenuItem item2 = new MenuItem("Preferences");
    item2.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("Preferences");
        }
    });

    final ContextMenu contextMenu = new ContextMenu(item1, item2);
    contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("showing");
        }
    });
    contextMenu.setOnShown(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("shown");
        }
    });

    System.out.println(contextMenu.onActionProperty());
    contextMenu.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("on");
        }
    });

    notification.setContextMenu(contextMenu);
    GridPane grid = new GridPane();
    grid.setVgap(4);
    grid.setHgap(10);
    grid.setPadding(new Insets(5, 5, 5, 5));
    grid.add(new Label("To: "), 0, 0);
    grid.add(notification, 1, 0);

    Group root = (Group) scene.getRoot();
    root.getChildren().add(grid);
    stage.setScene(scene);
    stage.show();
}

From source file:Main.java

@Override
public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    TextField notification = new TextField();

    MenuItem item1 = new MenuItem("About");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("About");
        }//from   w  ww  . j a v a2s .  c  o m
    });
    MenuItem item2 = new MenuItem("Preferences");
    item2.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("Preferences");
        }
    });

    final ContextMenu contextMenu = new ContextMenu(item1, item2);
    contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("showing");
        }
    });
    contextMenu.setOnShown(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("shown");
        }
    });

    System.out.println(contextMenu.onActionProperty());
    contextMenu.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("on");
        }
    });

    notification.setContextMenu(contextMenu);
    GridPane grid = new GridPane();
    grid.setVgap(4);
    grid.setHgap(10);
    grid.setPadding(new Insets(5, 5, 5, 5));
    grid.add(new Label("To: "), 0, 0);
    grid.add(notification, 1, 0);

    contextMenu.show(grid, 20, 20);

    Group root = (Group) scene.getRoot();
    root.getChildren().add(grid);
    stage.setScene(scene);
    stage.show();
}

From source file:Main.java

@Override
public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 450, 250);
    TextField notification = new TextField();

    MenuItem item1 = new MenuItem("About");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("About");
        }/*  w  ww .  j  a  v a  2 s .  c om*/
    });
    MenuItem item2 = new MenuItem("Preferences");
    item2.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("Preferences");
        }
    });

    final ContextMenu contextMenu = new ContextMenu(item1, item2);
    contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("showing");
        }
    });
    contextMenu.setOnShown(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("shown");
        }
    });

    System.out.println(contextMenu.onActionProperty());
    contextMenu.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("on");
        }
    });

    notification.setContextMenu(contextMenu);
    GridPane grid = new GridPane();
    grid.setVgap(4);
    grid.setHgap(10);
    grid.setPadding(new Insets(5, 5, 5, 5));
    grid.add(new Label("To: "), 0, 0);
    grid.add(notification, 1, 0);

    contextMenu.show(grid, Side.BOTTOM, 20, 20);

    Group root = (Group) scene.getRoot();
    root.getChildren().add(grid);
    stage.setScene(scene);
    stage.show();
}

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

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

            MenuItem exportItem = new MenuItem("Export");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if (!tooltip.isShowing())
            return;

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

        searchContext.clear();

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

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

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

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

From source file:Watcher.FXMLDocumentController.java

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

    try {//  w  w  w  .  j a  v a 2s . c o  m
        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());
            }
        }
    });
}