Example usage for javafx.scene.control ContextMenu ContextMenu

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

Introduction

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

Prototype

public ContextMenu() 

Source Link

Document

Create a new ContextMenu

Usage

From source file:Main.java

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

    final ContextMenu contextMenu = new ContextMenu();
    contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("showing");
        }//from  w ww  .ja  v  a 2  s  .c o m
    });
    contextMenu.setOnShown(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("shown");
        }
    });

    MenuItem item1 = new MenuItem("About");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("About");
        }
    });
    MenuItem item2 = new MenuItem("Preferences");
    item2.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("Preferences");
        }
    });
    contextMenu.getItems().addAll(item1, item2);

    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();

    final ContextMenu contextMenu = new ContextMenu();
    contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("showing");
        }//from ww w  .  ja v a2 s  . c  om
    });
    contextMenu.setOnShown(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("shown");
        }
    });

    MenuItem item1 = new MenuItem("About");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("About");
        }
    });
    MenuItem item2 = new MenuItem("Preferences");
    item2.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("Preferences");
        }
    });
    contextMenu.getItems().addAll(item1, item2);

    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) {
    stage.setTitle("ComboBoxSample");
    Scene scene = new Scene(new Group(), 450, 250);

    TextField notification = new TextField();

    final ContextMenu contextMenu = new ContextMenu();
    contextMenu.setOnShowing(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("showing");
        }/*from w  ww  .j a va  2 s  .  co m*/
    });
    contextMenu.setOnShown(new EventHandler<WindowEvent>() {
        public void handle(WindowEvent e) {
            System.out.println("shown");
        }
    });

    MenuItem item1 = new MenuItem("About");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("About");
        }
    });
    MenuItem item2 = new MenuItem("Preferences");
    item2.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            System.out.println("Preferences");
        }
    });
    contextMenu.getItems().addAll(item1, item2);

    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:account.management.controller.ViewSalaryVoucherController.java

/**
 * Initializes the controller class./*  w ww .ja  v  a2  s .c om*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    this.voucher_no.setCellValueFactory(new PropertyValueFactory("id"));
    this.date.setCellValueFactory(new PropertyValueFactory("date"));
    this.section.setCellValueFactory(new PropertyValueFactory("section"));
    this.name.setCellValueFactory(new PropertyValueFactory("name"));
    this.basis.setCellValueFactory(new PropertyValueFactory("basis"));
    this.amount.setCellValueFactory(new PropertyValueFactory("total"));

    final ContextMenu contextMenu = new ContextMenu();
    MenuItem item1 = new MenuItem("    View                  ");
    item1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            Data.salaryVoucher = table.getSelectionModel().getSelectedItem();

            try {
                Parent root = FXMLLoader
                        .load(getClass().getResource(MetaData.viewPath + "EditSalaryVoucher.fxml"));
                Scene scene = new Scene(root);
                Stage stage = new Stage();
                scene.setRoot(root);
                stage.setResizable(false);
                stage.setTitle("Salary Voucher");
                stage.setScene(scene);
                stage.showAndWait();
                int index = table.getSelectionModel().getSelectedIndex();
                getData();

            } catch (IOException ex) {
                Logger.getLogger(ViewSalaryVoucherController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });
    contextMenu.getItems().addAll(item1);
    this.table.setContextMenu(contextMenu);

}

From source file:org.beryx.viewreka.fxapp.codearea.ViewrekaCodeArea.java

public ViewrekaCodeArea() {
    applyConfiguration(CONFIG);/*from   ww  w .  j a va 2 s  .  co m*/

    ContextMenu cm = new ContextMenu();
    setPopupWindow(cm);
    setPopupAlignment(PopupAlignment.CARET_BOTTOM);
    setPopupAnchorOffset(new Point2D(-20, 1));
    cm.setOnShown(ev -> codeTemplatesCoordinates = new double[] { cm.getX(), cm.getY() });

    EventHandler<? super KeyEvent> tabHandler = EventHandlerHelper
            .on(EventPattern.keyPressed(KeyCode.SPACE, KeyCombination.CONTROL_DOWN))
            .act(ev -> showContextMenu(cm)).create();
    EventHandlerHelper.install(onKeyPressedProperty(), tabHandler);
}

From source file:com.github.douglasjunior.simpleCSVEditor.FXMLController.java

@Override
public void initialize(URL url, ResourceBundle rb) {
    file = new File("");
    csvFormat = CSVFormat.DEFAULT.withIgnoreEmptyLines(false);

    ContextMenu contextMenu = new ContextMenu();
    contextMenu.setAutoHide(true);/*  w w  w . j  ava  2  s  .com*/
    MenuItem inserirLinha = new MenuItem("Inserir linha");
    inserirLinha.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent t) {
            addNewRow();
            setNotSaved();
        }
    });

    contextMenu.getItems().add(inserirLinha);
    MenuItem removerLinha = new MenuItem("Remover linha");
    removerLinha.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent t) {
            deleteRow();
            setNotSaved();
        }
    });
    contextMenu.getItems().add(removerLinha);

    contextMenu.getItems().add(new SeparatorMenuItem());

    MenuItem inserirColuna = new MenuItem("Inserir coluna");
    inserirColuna.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            addNewColumn();
            setNotSaved();
        }
    });
    contextMenu.getItems().add(inserirColuna);

    MenuItem removerColuna = new MenuItem("Remover coluna");
    removerColuna.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            deleteColumn();
            setNotSaved();
        }
    });
    contextMenu.getItems().add(removerColuna);

    tableView.setContextMenu(contextMenu);
}

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 a  2 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:View.Visualize.java

public void getPieChartData(Integer nameColumn, Integer valueColumn, Table table, PieChart pieChart, Label lbl,
        Boolean newSeries, Boolean rowCounter) {
    data.clear();/*from w  ww .j a  v  a 2s.com*/

    if (!newSeries) {
        pieChart.getData().clear();
    }

    addDataFromTable(table, nameColumn, valueColumn, rowCounter);

    data.entrySet().stream().map(entry -> new PieChart.Data(entry.getKey(), entry.getValue()))
            .forEach(pieChart.getData()::add);

    for (PieChart.Data d : pieChart.getData()) {
        //deretter legger vi animasjon p piecharten.. 
        d.getNode().setOnMouseClicked(new mouseHooverAnimationPieChart.MouseHoverAnimation(d, pieChart));
        final Node n = d.getNode();
        Tooltip tooltip = new Tooltip();
        String toolTipText = "Value : " + d.getPieValue();
        tooltip.setText(toolTipText);
        Tooltip.install(n, tooltip);
        n.setOnMouseEntered(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                n.setEffect(glow);
            }
        });
        n.setOnMouseExited(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                n.setEffect(null);
            }
        });
        final ContextMenu contextMenu = new ContextMenu();
        MenuItem changeColor = new MenuItem("Change Color");
        MenuItem delete = new MenuItem("Standard color");
        ColorPicker cp = new ColorPicker();
        changeColor.setGraphic(cp);
        contextMenu.getItems().addAll(changeColor, delete);

        d.getNode().setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent t) {
                if (t.getButton() == MouseButton.SECONDARY) {
                    delete.setOnAction(new EventHandler() {
                        public void handle(Event t) {
                            d.getNode().setStyle("");
                        }

                    });

                    cp.setValue(null);
                    cp.setOnAction(new EventHandler() {
                        public void handle(Event t) {
                            String hex1 = "#" + Integer.toHexString(cp.getValue().hashCode());

                            d.getNode().setStyle("-fx-background-color: " + hex1 + ";");
                        }
                    });

                    contextMenu.show(d.getNode(), t.getScreenX(), t.getScreenY());
                }
            }

        });

    }

}

From source file:de.pixida.logtest.designer.automaton.AutomatonNode.java

@Override
ContextMenu createContextMenu() {/*from w  ww .ja v a2s .  co m*/
    final ContextMenu cm = new ContextMenu();

    MenuItem mi = new MenuItem("Create edge from here");
    mi.setGraphic(Icons.getIconGraphics("bullet_go"));
    mi.setOnAction(event -> {
        final AutomatonEdgeBuilder newEdge = new AutomatonEdgeBuilder(this.getGraph());
        this.getGraph().startDrawingConnector(this, newEdge);
    });
    cm.getItems().add(mi);

    mi = new MenuItem("Delete state");
    mi.setGraphic(Icons.getIconGraphics("delete"));
    mi.setStyle("-fx-text-fill:#FF3030");
    mi.setOnAction(event -> {
        final Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Confirm");
        alert.setHeaderText("You are about to delete the state.");
        alert.setContentText("Do you want to continue?");
        alert.showAndWait().filter(response -> response == ButtonType.OK)
                .ifPresent(response -> this.removeNodeAndEdges());
    });
    cm.getItems().add(mi);

    return cm;
}

From source file:ca.wumbo.doommanager.client.controller.file.DoomFileController.java

@FXML
private void initialize() {
    // Keep the left window the same size when resizing/maximizing.
    SplitPane.setResizableWithParent(leftBorderPane, false);

    // Allow selection of multiple cells.
    entryTreeTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    // Make the cells update accordingly.
    nameColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().entryProperty());
    sizeColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().dataLengthStringProperty());
    typeColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().entryTypeProperty());

    // Resize the splitter to a reasonable position.
    // Since we can't use Platform.runlater() to do this, we have to use a listener that removes itself.
    // Note: The old way it was done was to pass the tabPane's width to the function after this is initialized.
    InvalidationListener invalidationListener = new InvalidationListener() {
        @Override//from w w w  . j  a  va 2s .  c o  m
        public void invalidated(Observable observable) {
            setSplitterPosition((int) splitPane.getWidth());
            splitPane.widthProperty().removeListener(this); // Remove itself after the size is set.
        }
    };
    splitPane.widthProperty().addListener(invalidationListener);

    // Handle item selection. This will clean up our GUI and add/remove panes on the right of the splitter.
    entryTreeTable.getSelectionModel().selectedItemProperty().addListener((obsValue, oldValue, newValue) -> {
        updateGUIFromEntrySelection(oldValue, newValue);
    });

    // Support right clicking menus on the rows, source: https://gist.github.com/james-d/7758918
    entryTreeTable.setRowFactory(new Callback<TreeTableView<Entry>, TreeTableRow<Entry>>() {
        @Override
        public TreeTableRow<Entry> call(TreeTableView<Entry> tableView) {
            // Create the row to return.
            TreeTableRow<Entry> row = new TreeTableRow<>();
            ContextMenu contextMenu = new ContextMenu();

            // Whenever this row gets a new item (or is updated), rebuild the right click menu.
            row.itemProperty().addListener((observableValue, oldValue, newValue) -> {
                // TODO - Dynamically generate a new context menu - contextMenu.getItems().add(new MenuItem());
            });

            // Set context menu on row, but use a binding to make it only show for non-empty rows:
            row.contextMenuProperty()
                    .bind(Bindings.when(row.emptyProperty()).then((ContextMenu) null).otherwise(contextMenu));

            return row;
        }
    });

    // Instead of assigning graphics to each node, only do it for the cells.
    // This should help reduce object creation by having it only required for the visible rows.
    nameColumn.setCellFactory(new Callback<TreeTableColumn<Entry, Entry>, TreeTableCell<Entry, Entry>>() {
        @Override
        public TreeTableCell<Entry, Entry> call(TreeTableColumn<Entry, Entry> param) {
            return new TreeTableCell<Entry, Entry>() {
                @Override
                protected void updateItem(Entry item, boolean empty) {
                    super.updateItem(item, empty);
                    if (!empty && item != null) {
                        setText(item.getName());
                        Image img = resources.getImage(item.getClass().getSimpleName().toLowerCase());
                        setGraphic(new ImageView(img));
                    } else {
                        setText(null);
                        setGraphic(null);
                    }
                }
            };
        }
    });
}