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

private void addColorChangeOnIndividual(ObservableList<XYChart.Data> data) {

    final ContextMenu contextMenu = new ContextMenu();
    MenuItem changeColor = new MenuItem("Change Color");
    MenuItem delete = new MenuItem("Standard color");

    ColorPicker cp = new ColorPicker();
    changeColor.setGraphic(cp);//from  w w w.j  a  va  2  s.  c o m
    contextMenu.getItems().addAll(changeColor, delete);

    for (XYChart.Data d : data) {

        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:com.panemu.tiwulfx.table.TableControl.java

public TableControl(Class<R> recordClass) {
    this.recordClass = recordClass;
    initControls();//from   w w w  .j a va2s .  c o  m

    tblView.getSortOrder().addListener(new ListChangeListener<TableColumn<R, ?>>() {
        @Override
        public void onChanged(ListChangeListener.Change<? extends TableColumn<R, ?>> change) {
            reload();
        }
    });

    btnAdd.disableProperty().bind(mode.isEqualTo(Mode.EDIT));
    btnEdit.disableProperty().bind(mode.isNotEqualTo(Mode.READ));
    btnSave.disableProperty().bind(mode.isEqualTo(Mode.READ));
    btnDelete.disableProperty().bind(new BooleanBinding() {
        {
            super.bind(mode, tblView.getSelectionModel().selectedItemProperty(), lstChangedRow);
        }

        @Override
        protected boolean computeValue() {
            if ((mode.get() == Mode.INSERT && lstChangedRow.size() < 2)
                    || tblView.getSelectionModel().selectedItemProperty().get() == null
                    || mode.get() == Mode.EDIT) {
                return true;
            }
            return false;
        }
    });
    tblView.editableProperty().bind(mode.isNotEqualTo(Mode.READ));
    tblView.getSelectionModel().cellSelectionEnabledProperty().bind(tblView.editableProperty());
    mode.addListener(new ChangeListener<Mode>() {
        @Override
        public void changed(ObservableValue<? extends Mode> ov, Mode t, Mode t1) {
            if (t1 == Mode.READ) {
                directEdit = false;
            }
        }
    });

    tblView.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
            lblRowIndex
                    .setText(TiwulFXUtil.getLiteral("row.param", (page * maxResult.get() + t1.intValue() + 1)));
        }
    });

    tblView.getFocusModel().focusedCellProperty().addListener(new ChangeListener<TablePosition>() {
        @Override
        public void changed(ObservableValue<? extends TablePosition> observable, TablePosition oldValue,
                TablePosition newValue) {
            if (tblView.isEditable() && directEdit && agileEditing.get()) {
                tblView.edit(newValue.getRow(), newValue.getTableColumn());
            }
        }
    });

    tblView.setOnKeyPressed(new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent event) {
            if (event.getCode() == KeyCode.ESCAPE) {
                directEdit = false;
            } else if (event.getCode() == KeyCode.ENTER && mode.get() == Mode.READ) {
                getController().doubleClick(getSelectionModel().getSelectedItem());
            }
        }
    });

    /**
     * Define policy for TAB key press
     */
    tblView.addEventFilter(KeyEvent.KEY_PRESSED, tableKeyListener);
    /**
     * In INSERT mode, only inserted row that is focusable
     */
    tblView.getFocusModel().focusedCellProperty().addListener(tableFocusListener);

    tblView.setOnMouseReleased(tableRightClickListener);

    if (Platform.isFxApplicationThread()) {
        cm = new ContextMenu();
        cm.setAutoHide(true);
        setToolTips();
        /**
         * create custom row factory that can intercept double click on grid row
         */
        tblView.setRowFactory(new Callback<TableView<R>, TableRow<R>>() {
            @Override
            public TableRow<R> call(TableView<R> param) {
                return new TableRowControl(TableControl.this);
            }
        });
    }

    columns.addListener(new ListChangeListener<TableColumn<R, ?>>() {
        @Override
        public void onChanged(ListChangeListener.Change<? extends TableColumn<R, ?>> change) {
            while (change.next()) {
                if (change.wasAdded()) {
                    for (TableColumn<R, ?> column : change.getAddedSubList()) {
                        initColumn(column);
                    }
                }
                lastColumnIndex = getLeafColumns().size() - 1;
            }
        }
    });
    attachWindowVisibilityListener();
}

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

@Override
ContextMenu createContextMenu() {/*from   w ww.  jav a  2  s .com*/
    final ContextMenu cm = new ContextMenu();

    final MenuItem mi = new MenuItem("Delete edge");
    mi.setGraphic(Icons.getIconGraphics("delete"));
    mi.setStyle("-fx-text-fill:red");
    mi.setOnAction(event -> {
        final Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Confirm");
        alert.setHeaderText("You are about to delete the edge.");
        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:open.dolphin.client.MainWindowController.java

/**
 * Initializes the controller class./* w  ww  .ja  va2 s.  co  m*/
 *
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    //- Init TableView
    ReceptView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    PatientSearchView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    PatientFutureView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    LabRecieverView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    //        mainTab.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
    //            @Override
    //            public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) {
    //                SingleSelectionModel<Tab> selectionModel = mainTab.getSelectionModel();
    //                if(mainTab.getTabs() != null){
    //                    if(selectionModel.isSelected(0)){
    //                        karteTabPane.getTabs().clear();
    //                    }
    //                }
    //            }
    //        }); 

    // ?????
    TableColumn colId = new TableColumn("ID");
    recept.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("recept"));
    visitTime.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("visitTime"));
    tableCellAlignRight(visitTime);
    clientId.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("clientId"));
    name.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("name"));
    sex.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("sex"));
    tableCellAlignCenter(sex);
    insurance.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("insurance"));
    birthDay.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("birthDay"));
    physicianInCharge.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("physicianInCharge"));
    clinicalDepartments
            .setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("clinicalDepartments"));
    reservation.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("reservation"));
    memo.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("memo"));
    status.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("status"));
    tableCellImageAlignCenter(status);
    // ????
    ReceptView.getItems().setAll(fetchDataFromServer());

    // ???(?)
    ReceptView.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
                if (mouseEvent.getClickCount() == 2) {
                    System.out.println("Double clicked");
                    ReceptInfo selectedUser = ((TableView<ReceptInfo>) mouseEvent.getSource())
                            .getSelectionModel().getSelectedItem();
                    // ??????????
                    for (ReceptInfo info : receptList) {
                        if (info.getName().equals(selectedUser.getName())) {
                            return;
                        }
                    }
                    System.out.println(selectedUser.getClientId());
                    receptList.add(selectedUser);
                    // ??
                    final ContextMenu contextMenu = new ContextMenu();
                    MenuItem item1 = new MenuItem("?");
                    item1.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Reserve Karte?");
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item2 = new MenuItem("???");
                    item2.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab and Preservation???");
                            karteTabPane.getTabs().remove(karteTabPane.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item3 = new MenuItem("?");
                    item3.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab?");
                            karteTabPane.getTabs().remove(karteTabPane.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    contextMenu.getItems().addAll(item1, item2, item3);

                    Tab tab = new Tab(selectedUser.getName());
                    tab.setOnClosed(new EventHandler<Event>() {
                        @Override
                        public void handle(Event t) {
                            Tab tab = (Tab) t.getSource();
                            for (int i = 0; i < receptList.size(); i++) {
                                if (tab.getText().equals(receptList.get(i).getName())) {
                                    receptList.remove(i);
                                }
                            }
                            System.out.println("Closed!");
                        }
                    });
                    tab.setContextMenu(contextMenu); // Right-click mouse button menu
                    try {
                        // Loading content on demand
                        Parent root = (Parent) new FXMLLoader()
                                .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream());
                        tab.setContent(root);
                        karteTabPane.getSelectionModel().select(tab);
                        karteTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
                        karteTabPane.getTabs().add(tab);
                        karteTabPane.setPrefSize(kartePane.getPrefWidth(), kartePane.getPrefHeight());
                        kartePane.getChildren().retainAll();
                        kartePane.getChildren().add(karteTabPane);
                    } catch (IOException ex) {
                        Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
        }
    });

    // ????
    clientId1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("clientId1"));
    name1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("name1"));
    kana1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("kana1"));
    sex1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("sex1"));
    birthDay1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("birthDay1"));
    receiveDay1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("receiveDay1"));
    status1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("status1"));
    // dummy?
    PatientSearchView.getItems().setAll(fetchDataFromPatientInfo());

    // ??(?)
    PatientSearchView.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
                if (mouseEvent.getClickCount() == 2) {
                    System.out.println("Double clicked");
                    PatientSearchInfo selectedUser = ((TableView<PatientSearchInfo>) mouseEvent.getSource())
                            .getSelectionModel().getSelectedItem();
                    // ??????????
                    for (PatientSearchInfo info : patientSearchList) {
                        if (info.getName1().equals(selectedUser.getName1())) {
                            return;
                        }
                    }
                    System.out.println(selectedUser.getKana1());
                    patientSearchList.add(selectedUser);
                    // ??
                    final ContextMenu contextMenu = new ContextMenu();
                    MenuItem item1 = new MenuItem("?");
                    item1.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Reserve Karte?");
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item2 = new MenuItem("???");
                    item2.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab and Preservation???");
                            karteTabPane1.getTabs().remove(karteTabPane1.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item3 = new MenuItem("?");
                    item3.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab?");
                            karteTabPane1.getTabs().remove(karteTabPane1.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    contextMenu.getItems().addAll(item1, item2, item3);

                    Tab tab = new Tab(selectedUser.getName1());
                    tab.setOnClosed(new EventHandler<Event>() {
                        @Override
                        public void handle(Event t) {
                            Tab tab = (Tab) t.getSource();
                            for (int i = 0; i < patientSearchList.size(); i++) {
                                if (tab.getText().equals(patientSearchList.get(i).getName1())) {
                                    patientSearchList.remove(i);
                                }
                            }
                            System.out.println("Closed!");
                        }
                    });
                    tab.setContextMenu(contextMenu); // Right-click mouse button menu
                    try {
                        // Loading content on demand
                        Parent root = (Parent) new FXMLLoader()
                                .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream());
                        tab.setContent(root);
                        karteTabPane1.getSelectionModel().select(tab);
                        karteTabPane1.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
                        karteTabPane1.getTabs().add(tab);
                        karteTabPane1.setPrefSize(kartePane1.getPrefWidth(), kartePane1.getPrefHeight());
                        kartePane1.getChildren().retainAll();
                        kartePane1.getChildren().add(karteTabPane1);
                    } catch (IOException ex) {
                        Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    });

    // ????
    clientId2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("clientId2"));
    name2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("name2"));
    kana2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("kana2"));
    insurance2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("insurance2"));
    sex2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("sex2"));
    birthDay2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("birthDay2"));
    physicianInCharge2
            .setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("physicianInCharge2"));
    clinicalDepartments2
            .setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("clinicalDepartments2"));
    karte2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("karte2"));
    // dummy?
    PatientFutureView.getItems().setAll(fetchDataFromPatientFutureInfo());

    // ??(?)
    PatientFutureView.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
                if (mouseEvent.getClickCount() == 2) {
                    System.out.println("Double clicked");
                    PatientFutureInfo selectedUser = ((TableView<PatientFutureInfo>) mouseEvent.getSource())
                            .getSelectionModel().getSelectedItem();
                    System.out.println(selectedUser.getName2());
                    // ??
                    final ContextMenu contextMenu = new ContextMenu();
                    MenuItem item1 = new MenuItem("?");
                    item1.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Reserve Karte?");
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item2 = new MenuItem("???");
                    item2.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab and Preservation???");
                            karteTabPane2.getTabs().remove(karteTabPane2.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item3 = new MenuItem("?");
                    item3.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab?");
                            karteTabPane2.getTabs().remove(karteTabPane2.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    contextMenu.getItems().addAll(item1, item2, item3);

                    Tab tab = new Tab(selectedUser.getName2());
                    tab.setContextMenu(contextMenu); // Right-click mouse button menu
                    try {
                        // Loading content on demand
                        Parent root = (Parent) new FXMLLoader()
                                .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream());
                        tab.setContent(root);
                        karteTabPane2.getSelectionModel().select(tab);
                        karteTabPane2.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
                        karteTabPane2.getTabs().add(tab);
                        karteTabPane2.setPrefSize(kartePane2.getPrefWidth(), kartePane2.getPrefHeight());
                        kartePane2.getChildren().retainAll();
                        kartePane2.getChildren().add(karteTabPane2);
                    } catch (IOException ex) {
                        Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
        }
    });

    // ?????
    lab3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("lab3"));
    clientId3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("clientId3"));
    kana3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("kana3"));
    karteKana3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("karteKana3"));
    sex3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("sex3"));
    karteSex3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("karteSex3"));
    sampleGetDay3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("sampleGetDay3"));
    register3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("register3"));
    status3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("status3"));
    // dummy?
    LabRecieverView.getItems().setAll(fetchDataFromLabRecieverInfo());

    // ???(?)
    LabRecieverView.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
                if (mouseEvent.getClickCount() == 2) {
                    System.out.println("Double clicked");
                    LabReceiverInfo selectedUser = ((TableView<LabReceiverInfo>) mouseEvent.getSource())
                            .getSelectionModel().getSelectedItem();
                    System.out.println(selectedUser.getKana3());
                    // ??
                    final ContextMenu contextMenu = new ContextMenu();
                    MenuItem item1 = new MenuItem("?");
                    item1.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Reserve Karte?");
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item2 = new MenuItem("???");
                    item2.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab and Preservation???");
                            karteTabPane3.getTabs().remove(karteTabPane3.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    MenuItem item3 = new MenuItem("?");
                    item3.setOnAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            System.out.println("Close Tab?");
                            karteTabPane3.getTabs().remove(karteTabPane3.getSelectionModel().getSelectedItem());
                            // ??
                            // e.getSource();
                        }
                    });
                    contextMenu.getItems().addAll(item1, item2, item3);

                    Tab tab = new Tab(selectedUser.getKana3());
                    tab.setContextMenu(contextMenu); // Right-click mouse button menu
                    try {
                        // Loading content on demand
                        Parent root = (Parent) new FXMLLoader()
                                .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream());
                        tab.setContent(root);
                        karteTabPane3.getSelectionModel().select(tab);
                        karteTabPane3.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
                        karteTabPane3.getTabs().add(tab);
                        karteTabPane3.setPrefSize(kartePane3.getPrefWidth(), kartePane3.getPrefHeight());
                        kartePane3.getChildren().retainAll();
                        kartePane3.getChildren().add(karteTabPane3);
                    } catch (IOException ex) {
                        Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
        }
    });

    // ??5??????
    Timer exeTimer = new Timer();
    Calendar cal = Calendar.getInstance();
    final int sec = cal.get(Calendar.SECOND);
    int delay = (60 - sec) * 1000;
    int interval = 5 * 1000;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (!stopFlag) {
                System.out.println("this is called every 5 seconds on UI thread");
                receptUpdate();
            } else {
                this.cancel();
            }
        }
    };
    exeTimer.schedule(task, delay, interval);

}

From source file:View.Visualize.java

private void addColorChangeOnSeries(XYChart.Series series) {

    final ContextMenu contextMenu = new ContextMenu();
    MenuItem changeColor = new MenuItem("Change color");
    MenuItem delete = new MenuItem("Standard color");
    ColorPicker cp = new ColorPicker();
    changeColor.setGraphic(cp);//from w  ww  . jav a2 s . c o  m
    contextMenu.getItems().addAll(changeColor, delete);

    Node d = series.getNode();

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

        @Override
        public void handle(MouseEvent t) {
            if (t.getButton() == MouseButton.SECONDARY) {
                delete.setOnAction(new EventHandler() {
                    public void handle(Event t) {
                        if (series.getChart() instanceof StackedAreaChart) {
                            series.getChart().lookup(".default-color" + series.getNode().getUserData()
                                    + ".chart-series-area-fill").setStyle("");
                        }
                        if (series.getChart() instanceof LineChart) {
                            series.getChart().lookup(
                                    ".default-color" + series.getNode().getUserData() + ".chart-series-line")
                                    .setStyle("");
                        }
                    }

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

                        if (series.getChart() instanceof StackedAreaChart) {
                            series.getChart().lookup(".default-color" + series.getNode().getUserData()
                                    + ".chart-series-area-fill").setStyle("-fx-fill:" + hex1 + ";");
                        }
                        if (series.getChart() instanceof LineChart) {
                            series.getChart().lookup(
                                    ".default-color" + series.getNode().getUserData() + ".chart-series-line")
                                    .setStyle("-fx-stroke:" + hex1 + ";");
                        }

                    }
                });

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

    });
}

From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java

private void setupTableWithChanges(TableView<Change> tv, Dataset tp) {
    tv.setEditable(true);/*from w w w. ja va  2s . co  m*/
    tv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    tv.getColumns().clear();

    TableColumn<Change, ChangeType> colChangeType = new TableColumn<>("Type");
    colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(),
            ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT,
            ChangeType.COMPLEX, ChangeType.ERROR));
    colChangeType.setCellValueFactory(new PropertyValueFactory<>("type"));
    colChangeType.setPrefWidth(100.0);
    colChangeType.setEditable(true);
    tv.getColumns().add(colChangeType);

    TableColumn<Change, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From");
    colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from"));
    colChangeFrom.setPrefWidth(200.0);
    colChangeFrom.setEditable(true);
    tv.getColumns().add(colChangeFrom);

    TableColumn<Change, ObservableSet<Name>> colChangeTo = new TableColumn<>("To");
    colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to"));
    colChangeTo.setPrefWidth(200.0);
    colChangeTo.setEditable(true);
    tv.getColumns().add(colChangeTo);

    TableColumn<Change, String> colExplicit = new TableColumn<>("Explicit or implicit?");
    colExplicit.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getDataset().isChangeImplicit(features.getValue()) ? "Implicit"
                            : "Explicit"));
    tv.getColumns().add(colExplicit);

    ChangeFilter cf = datasetView.getProjectView().getProject().getChangeFilter();
    TableColumn<Change, String> colFiltered = new TableColumn<>("Eliminated by filter?");
    colFiltered.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    cf.test(features.getValue()) ? "Allowed" : "Eliminated"));
    tv.getColumns().add(colFiltered);

    TableColumn<Change, String> colNote = new TableColumn<>("Note");
    colNote.setCellFactory(TextFieldTableCell.forTableColumn());
    colNote.setCellValueFactory(new PropertyValueFactory<>("note"));
    colNote.setPrefWidth(100.0);
    colNote.setEditable(true);
    tv.getColumns().add(colNote);

    TableColumn<Change, String> colCitations = new TableColumn<>("Citations");
    colCitations.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted()
                            .collect(Collectors.joining("; "))));
    tv.getColumns().add(colCitations);

    TableColumn<Change, String> colGenera = new TableColumn<>("Genera");
    colGenera.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus())
                            .distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colGenera);

    TableColumn<Change, String> colSpecificEpithet = new TableColumn<>("Specific epithets");
    colSpecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(String
                    .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet())
                            .filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colSpecificEpithet);

    // The infraspecific string.
    TableColumn<Change, String> colInfraspecificEpithet = new TableColumn<>("Infraspecific epithets");
    colInfraspecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ",
                            features.getValue().getAllNames().stream()
                                    .map(n -> n.getInfraspecificEpithetsAsString()).filter(s -> s != null)
                                    .distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colInfraspecificEpithet);

    // The very last epithet of all
    TableColumn<Change, String> colTerminalEpithet = new TableColumn<>("Terminal epithet");
    colTerminalEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> {
                        List<Name.InfraspecificEpithet> infraspecificEpithets = n.getInfraspecificEpithets();
                        if (!infraspecificEpithets.isEmpty()) {
                            return infraspecificEpithets.get(infraspecificEpithets.size() - 1).getValue();
                        } else {
                            return n.getSpecificEpithet();
                        }
                    }).filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colTerminalEpithet);

    // Properties
    TableColumn<Change, String> colProperties = new TableColumn<>("Properties");
    colProperties.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getProperties().entrySet().stream()
                            .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted()
                            .collect(Collectors.joining("; "))));
    tv.getColumns().add(colProperties);

    fillTableWithChanges(tv, tp);

    // When someone selects a cell in the Table, try to select the appropriate data in the
    // additional data view.
    tv.getSelectionModel().getSelectedItems().addListener((ListChangeListener<Change>) lcl -> {
        AdditionalData aData = additionalDataCombobox.getSelectionModel().getSelectedItem();

        if (aData != null) {
            aData.onSelectChange(tv.getSelectionModel().getSelectedItems());
        }
    });

    // Create a right-click menu for table rows.
    changesTableView.setRowFactory(table -> {
        TableRow<Change> row = new TableRow<>();

        row.setOnContextMenuRequested(event -> {
            if (row.isEmpty())
                return;

            // We don't currently use the clicked change, since currently all options
            // change *all* the selected changes, but this may change in the future.
            Change change = row.getItem();

            ContextMenu changeMenu = new ContextMenu();

            Menu searchForName = new Menu("Search for name");
            searchForName.getItems().addAll(
                    change.getAllNames().stream().sorted().map(n -> createMenuItem(n.getFullName(), action -> {
                        datasetView.getProjectView().openDetailedView(n);
                    })).collect(Collectors.toList()));
            changeMenu.getItems().add(searchForName);
            changeMenu.getItems().add(new SeparatorMenuItem());

            changeMenu.getItems().add(createMenuItem("Edit note", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());

                String combinedNotes = changes.stream().map(ch -> ch.getNote().orElse("").trim()).distinct()
                        .collect(Collectors.joining("\n")).trim();

                Optional<String> result = askUserForTextArea(
                        "Modify the note for these " + changes.size() + " changes:", combinedNotes);

                if (result.isPresent()) {
                    String note = result.get().trim();
                    LOGGER.info("Using 'Edit note' to set note to '" + note + "' on changes " + changes);
                    changes.forEach(ch -> ch.noteProperty().set(note));
                }
            }));
            changeMenu.getItems().add(new SeparatorMenuItem());

            // Create a submenu for tags and urls.
            String note = change.noteProperty().get();

            Menu removeTags = new Menu("Tags");
            removeTags.getItems().addAll(change.getTags().stream().sorted()
                    .map(tag -> new MenuItem(tag.getName())).collect(Collectors.toList()));

            Menu lookupURLs = new Menu("Lookup URL");
            change.getURIs().stream().sorted().map(uri -> {
                return createMenuItem(uri.toString(), evt -> {
                    try {
                        Desktop.getDesktop().browse(uri);
                    } catch (IOException ex) {
                        LOGGER.warning("Could not open URL '" + uri + "': " + ex);
                    }
                });
            }).forEach(mi -> lookupURLs.getItems().add(mi));
            changeMenu.getItems().add(lookupURLs);

            changeMenu.getItems().add(new SeparatorMenuItem());
            changeMenu.getItems().add(createMenuItem("Prepend text to all notes", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());

                Optional<String> result = askUserForTextField(
                        "Enter tags to prepend to notes in " + changes.size() + " changes:");

                if (result.isPresent()) {
                    String tags = result.get().trim();
                    changes.forEach(ch -> {
                        String prevValue = change.getNote().orElse("").trim();

                        LOGGER.info("Prepending tags '" + tags + "' to previous value '" + prevValue
                                + "' for change " + ch);

                        ch.noteProperty().set((tags + " " + prevValue).trim());
                    });
                }
            }));
            changeMenu.getItems().add(createMenuItem("Append text to all notes", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());
                Optional<String> result = askUserForTextField(
                        "Enter tags to append to notes in " + changes.size() + " changes:");

                if (result.isPresent()) {
                    String tags = result.get().trim();
                    changes.forEach(ch -> {
                        String prevValue = ch.getNote().orElse("").trim();

                        LOGGER.info("Appending tags '" + tags + "' to previous value '" + prevValue
                                + "' for change " + ch);

                        ch.noteProperty().setValue((prevValue + " " + tags).trim());
                    });
                }
            }));

            changeMenu.show(datasetView.getScene().getWindow(), event.getScreenX(), event.getScreenY());

        });

        return row;
    });

    LOGGER.info("setupTableWithChanges() completed");
}

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

private ContextMenu createContextMenu(TreeView<Object> elements) {
    ContextMenu contextMenu = new ContextMenu();
    InvalidationListener il = observable1 -> updateContextMenu(contextMenu, elements);
    elements.rootProperty().addListener(il);
    elements.getSelectionModel().selectedItemProperty().addListener(il);
    return contextMenu;
}

From source file:dpfmanager.shell.interfaces.gui.component.report.ReportsView.java

public void addFormatIcons() {
    colFormats.setCellFactory(/*from ww  w  . j av a2s  . co m*/
            new Callback<TableColumn<ReportRow, ObservableMap<String, String>>, TableCell<ReportRow, ObservableMap<String, String>>>() {
                @Override
                public TableCell<ReportRow, ObservableMap<String, String>> call(
                        TableColumn<ReportRow, ObservableMap<String, String>> param) {
                    TableCell<ReportRow, ObservableMap<String, String>> cell = new TableCell<ReportRow, ObservableMap<String, String>>() {
                        @Override
                        public void updateItem(ObservableMap<String, String> item, boolean empty) {
                            super.updateItem(item, empty);
                            if (!empty && item != null) {

                                HBox box = new HBox();
                                box.setSpacing(3);
                                box.setAlignment(Pos.CENTER_LEFT);

                                for (String i : item.keySet()) {
                                    ImageView icon = new ImageView();
                                    icon.setId("but" + i);
                                    icon.setFitHeight(20);
                                    icon.setFitWidth(20);
                                    icon.setImage(new Image("images/formats/" + i + ".png"));
                                    icon.setCursor(Cursor.HAND);

                                    String type = i;
                                    String path = item.get(i);
                                    icon.setOnMouseClicked(new EventHandler<MouseEvent>() {
                                        @Override
                                        public void handle(MouseEvent event) {
                                            ArrayMessage am = new ArrayMessage();
                                            am.add(GuiConfig.PERSPECTIVE_SHOW, new UiMessage());
                                            am.add(GuiConfig.PERSPECTIVE_SHOW + "." + GuiConfig.COMPONENT_SHOW,
                                                    new ShowMessage(type, path));
                                            getContext().send(GuiConfig.PERSPECTIVE_SHOW, am);
                                        }
                                    });

                                    ContextMenu contextMenu = new ContextMenu();
                                    javafx.scene.control.MenuItem download = new javafx.scene.control.MenuItem(
                                            "Download report");
                                    contextMenu.getItems().add(download);
                                    icon.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
                                        public void handle(ContextMenuEvent e) {
                                            contextMenu.show(icon, e.getScreenX(), e.getScreenY());
                                        }
                                    });
                                    box.getChildren().add(icon);
                                }

                                setGraphic(box);
                            } else {
                                setGraphic(null);
                            }
                        }
                    };
                    return cell;
                }
            });
}

From source file:com.ggvaidya.scinames.dataset.BinomialChangesSceneController.java

private void setupTableWithBinomialChanges() {
    changesTableView.setEditable(false);
    changesTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    changesTableView.setItems(potentialChanges);

    changesTableView.getColumns().clear();

    TableColumn<PotentialChange, ChangeType> colChangeType = new TableColumn<>("Type");
    colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(),
            ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT,
            ChangeType.COMPLEX, ChangeType.ERROR));
    colChangeType.setCellValueFactory(new PropertyValueFactory<>("type"));
    colChangeType.setPrefWidth(100.0);/* w  w w . ja va 2  s  .c o m*/
    colChangeType.setEditable(true);
    changesTableView.getColumns().add(colChangeType);

    TableColumn<PotentialChange, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From");
    colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from"));
    colChangeFrom.setPrefWidth(200.0);
    colChangeFrom.setEditable(true);
    changesTableView.getColumns().add(colChangeFrom);

    TableColumn<PotentialChange, ObservableSet<Name>> colChangeTo = new TableColumn<>("To");
    colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to"));
    colChangeTo.setPrefWidth(200.0);
    colChangeTo.setEditable(true);
    changesTableView.getColumns().add(colChangeTo);

    TableColumn<PotentialChange, String> colDataset = new TableColumn<>("Dataset");
    colDataset.setCellValueFactory(cvf -> {
        return new ReadOnlyStringWrapper(cvf.getValue().getDataset().toString());
    });
    colDataset.setPrefWidth(150.0);
    changesTableView.getColumns().add(colDataset);

    TableColumn<PotentialChange, SimplifiedDate> dateCol = new TableColumn<>("Date");
    dateCol.setCellFactory(
            TextFieldTableCell.forTableColumn(new SimplifiedDate.SimplifiedDateStringConverter()));
    dateCol.setCellValueFactory(cvf -> new ReadOnlyObjectWrapper<>(cvf.getValue().getDataset().getDate()));
    dateCol.setPrefWidth(150);
    dateCol.setSortable(true);
    dateCol.setSortType(SortType.ASCENDING);
    changesTableView.getColumns().add(dateCol);
    changesTableView.getSortOrder().add(dateCol);

    TableColumn<PotentialChange, String> colChangeSummary = new TableColumn<>("Changes summary");
    colChangeSummary.setCellValueFactory(cvf -> {
        Set<Change> changes = changesByPotentialChange.get(cvf.getValue());
        return new ReadOnlyStringWrapper(changes.size() + ": "
                + changes.stream().map(ch -> ch.toString()).collect(Collectors.joining("; ")));
    });
    colChangeSummary.setPrefWidth(200.0);
    changesTableView.getColumns().add(colChangeSummary);

    /*
    TableColumn<PotentialChange, String> colExplicit = new TableColumn<>("Explicit or implicit?");
    colExplicit.setCellValueFactory(
       (TableColumn.CellDataFeatures<Change, String> features) -> 
    new ReadOnlyStringWrapper(
       features.getValue().getDataset().isChangeImplicit(features.getValue()) ? "Implicit" : "Explicit"
    )
    );
    tv.getColumns().add(colExplicit);
            
    ChangeFilter cf = binomialChangesView.getProjectView().getProject().getChangeFilter();
    TableColumn<Change, String> colFiltered = new TableColumn<>("Eliminated by filter?");
    colFiltered.setCellValueFactory(
       (TableColumn.CellDataFeatures<Change, String> features) -> 
    new ReadOnlyStringWrapper(
       cf.test(features.getValue()) ? "Allowed" : "Eliminated"
    )
    );
    tv.getColumns().add(colFiltered);
    */

    TableColumn<PotentialChange, String> colNote = new TableColumn<>("Note");
    colNote.setCellFactory(TextFieldTableCell.forTableColumn());
    colNote.setCellValueFactory(new PropertyValueFactory<>("note"));
    colNote.setPrefWidth(100.0);
    changesTableView.getColumns().add(colNote);

    TableColumn<PotentialChange, String> colReason = new TableColumn<>("Reason");
    colReason.setCellValueFactory(cvf -> new ReadOnlyStringWrapper(calculateReason(cvf.getValue())));
    colReason.setPrefWidth(100.0);
    changesTableView.getColumns().add(colReason);

    TableColumn<PotentialChange, String> colReasonDate = new TableColumn<>("ReasonDate");
    colReasonDate.setCellValueFactory(cvf -> {
        String result;
        Set<SimplifiedDate> dates = calculateReasonDate(cvf.getValue());

        if (dates.size() > 1) {
            result = "(" + dates.size() + ") " + dates.stream().distinct().sorted()
                    .map(sd -> sd.asYYYYmmDD("-")).collect(Collectors.joining("|"));

        } else if (dates.size() == 1) {
            result = dates.iterator().next().asYYYYmmDD("-");

        } else {
            result = "NA";
        }

        return new ReadOnlyStringWrapper(result);
    });
    colReasonDate.setPrefWidth(100.0);
    changesTableView.getColumns().add(colReasonDate);

    TableColumn<PotentialChange, String> colCitations = new TableColumn<>("Citations");
    colCitations.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted()
                            .collect(Collectors.joining("; "))));
    changesTableView.getColumns().add(colCitations);

    TableColumn<PotentialChange, String> colGenera = new TableColumn<>("Genera");
    colGenera.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus())
                            .distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colGenera);

    TableColumn<PotentialChange, String> colSpecificEpithet = new TableColumn<>("Specific epithets");
    colSpecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(String
                    .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet())
                            .filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colSpecificEpithet);

    // The infraspecific string.
    TableColumn<PotentialChange, String> colInfraspecificEpithet = new TableColumn<>("Infraspecific epithets");
    colInfraspecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ",
                            features.getValue().getAllNames().stream()
                                    .map(n -> n.getInfraspecificEpithetsAsString()).filter(s -> s != null)
                                    .distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colInfraspecificEpithet);

    // The very last epithet of all
    TableColumn<PotentialChange, String> colTerminalEpithet = new TableColumn<>("Terminal epithet");
    colTerminalEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> {
                        List<Name.InfraspecificEpithet> infraspecificEpithets = n.getInfraspecificEpithets();
                        if (!infraspecificEpithets.isEmpty()) {
                            return infraspecificEpithets.get(infraspecificEpithets.size() - 1).getValue();
                        } else {
                            return n.getSpecificEpithet();
                        }
                    }).filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    changesTableView.getColumns().add(colTerminalEpithet);

    TableColumn<PotentialChange, String> dateForRCol = new TableColumn<>("DateYMD");
    dateForRCol.setCellValueFactory(
            cvf -> new ReadOnlyObjectWrapper<>(cvf.getValue().getDataset().getDate().asYYYYmmDD("-")));
    changesTableView.getColumns().add(dateForRCol);

    // Properties
    TableColumn<PotentialChange, String> colProperties = new TableColumn<>("Properties");
    colProperties.setCellValueFactory(
            (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getProperties().entrySet().stream()
                            .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted()
                            .collect(Collectors.joining("; "))));
    changesTableView.getColumns().add(colProperties);

    fillTableWithBinomialChanges();

    // When someone selects a cell in the Table, try to select the appropriate data in the
    // additional data view.
    changesTableView.getSelectionModel().getSelectedItems()
            .addListener((ListChangeListener<PotentialChange>) lcl -> {
                AdditionalData aData = additionalDataCombobox.getSelectionModel().getSelectedItem();

                if (aData != null) {
                    aData.onSelectChange(changesTableView.getSelectionModel().getSelectedItems());
                }
            });

    // Create a right-click menu for table rows.
    changesTableView.setRowFactory(table -> {
        TableRow<PotentialChange> row = new TableRow<>();

        row.setOnContextMenuRequested(event -> {
            if (row.isEmpty())
                return;

            // We don't currently use the clicked change, since currently all options
            // change *all* the selected changes, but this may change in the future.
            PotentialChange change = row.getItem();

            ContextMenu changeMenu = new ContextMenu();

            Menu lookupChange = new Menu("Look up change");
            lookupChange.getItems().addAll(changesByPotentialChange.getOrDefault(change, new HashSet<>())
                    .stream()
                    .map(ch -> createMenuItem(ch.toString() + " in " + ch.getDataset().toString(), action -> {
                        binomialChangesView.getProjectView().openDetailedView(ch);
                    })).collect(Collectors.toList()));
            changeMenu.getItems().add(lookupChange);

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

            Menu searchForName = new Menu("Search for name");
            searchForName.getItems().addAll(
                    change.getAllNames().stream().sorted().map(n -> createMenuItem(n.getFullName(), action -> {
                        binomialChangesView.getProjectView().openDetailedView(n);
                    })).collect(Collectors.toList()));
            changeMenu.getItems().add(searchForName);

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

            // Create a submenu for tags and urls.
            String note = change.noteProperty().get();

            Menu removeTags = new Menu("Tags");
            removeTags.getItems().addAll(change.getTags().stream().sorted()
                    .map(tag -> new MenuItem(tag.getName())).collect(Collectors.toList()));

            Menu lookupURLs = new Menu("Lookup URL");
            change.getURIs().stream().sorted().map(uri -> {
                return createMenuItem(uri.toString(), evt -> {
                    try {
                        Desktop.getDesktop().browse(uri);
                    } catch (IOException ex) {
                        LOGGER.warning("Could not open URL '" + uri + "': " + ex);
                    }
                });
            }).forEach(mi -> lookupURLs.getItems().add(mi));
            changeMenu.getItems().add(lookupURLs);

            changeMenu.show(binomialChangesView.getScene().getWindow(), event.getScreenX(), event.getScreenY());

        });

        return row;
    });

    LOGGER.info("setupTableWithChanges() completed");
}

From source file:snpviewer.SnpViewer.java

@Override
public void initialize(URL url, ResourceBundle rb) {
    labelSplitPane.setDividerPositions();
    chromSplitPane.setDividerPositions();
    Pane lpane = (Pane) horizontalSplit.getItems().get(0);
    SplitPane.setResizableWithParent(lpane, false);
    //mnemonics/shortcuts for menus        
    mainMenu.useSystemMenuBarProperty().set(true);
    fileMenu.setMnemonicParsing(true);// w ww. ja  v a 2  s . c  o m
    sampleMenu.setMnemonicParsing(true);
    goMenu.setMnemonicParsing(true);
    helpMenu.setMnemonicParsing(true);
    newProjectMenu.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.SHORTCUT_DOWN));
    loadProjectMenu.setAccelerator(new KeyCodeCombination(KeyCode.L, KeyCombination.SHORTCUT_DOWN));
    addAffSampleMenu.setAccelerator(
            new KeyCodeCombination(KeyCode.A, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    addUnSampleMenu.setAccelerator(
            new KeyCodeCombination(KeyCode.U, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    nextChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.EQUALS, KeyCombination.SHORTCUT_DOWN));
    prevChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.MINUS, KeyCombination.SHORTCUT_DOWN));
    firstChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.DIGIT1, KeyCombination.SHORTCUT_DOWN));
    lastChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.DIGIT0, KeyCombination.SHORTCUT_DOWN));
    redrawMenu.setAccelerator(new KeyCodeCombination(KeyCode.R, KeyCombination.SHORTCUT_DOWN));
    cacheChromsMenu.setAccelerator(
            new KeyCodeCombination(KeyCode.C, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    saveToPngMenu.setAccelerator(
            new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    autoFindRegions.setAccelerator(new KeyCodeCombination(KeyCode.F, KeyCombination.SHORTCUT_DOWN));
    //need to disable hideSavedRegionsMenu accelerator for linux - doesn't work for check menus
    hideSavedRegionsMenu.setAccelerator(
            new KeyCodeCombination(KeyCode.H, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    clearSavedRegionsMenu.setAccelerator(
            new KeyCodeCombination(KeyCode.X, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    displaySavedsRegionsMenu.setAccelerator(new KeyCodeCombination(KeyCode.T, KeyCombination.SHORTCUT_DOWN));
    outputSavedRegionsMenu.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN));
    removeSampleMenu.setAccelerator(
            new KeyCodeCombination(KeyCode.R, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    //set radio menu item toggle group
    ArrayList<RadioMenuItem> callQualityRadios = new ArrayList<>(
            Arrays.asList(noFilteringRadio, filter99, filter95, filter90, filter85));
    ToggleGroup callQualityToggle = new ToggleGroup();
    for (RadioMenuItem r : callQualityRadios) {
        r.setToggleGroup(callQualityToggle);
    }
    noFilteringRadio.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            setQualityFilter(null);
        }
    });

    filter99.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            setQualityFilter(0.01);
        }
    });

    filter95.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            setQualityFilter(0.05);
        }
    });

    filter90.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            setQualityFilter(0.10);
        }
    });

    filter85.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            setQualityFilter(0.15);
        }
    });

    nextChromMenu.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            selectNextChromosome(true);
        }
    });

    prevChromMenu.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            selectNextChromosome(false);
        }
    });

    firstChromMenu.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            if (!cancelButton.isDisabled()) {
                cancelButton.fire();
            }
            if (!chromosomeSelector.isDisabled()) {

                chromosomeSelector.getSelectionModel().selectFirst();
            }
        }
    });

    lastChromMenu.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            if (!cancelButton.isDisabled()) {
                cancelButton.fire();
            }
            if (!chromosomeSelector.isDisabled()) {
                chromosomeSelector.getSelectionModel().selectLast();
            }
        }
    });

    hideSavedRegionsMenu.setOnAction(new EventHandler() {
        @Override
        public void handle(Event ev) {
            showHideSavedRegions();
        }
    });

    colorComp.addAll(Arrays.asList(colorComponants));

    //selection context menu
    final ContextMenu scm = new ContextMenu();
    final MenuItem scmItem1 = new MenuItem("Display Flanking SNP IDs");
    scmItem1.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            /* get coordinates of selection and report back
             * flanking snp ids and coordinates
             */
            displayFlankingSnpIDs(dragSelectRectangle);

        }
    });
    final MenuItem scmItem2 = new MenuItem("Write Selected Region to File");
    scmItem2.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    /* get coordinates of selection and report back
                     * write SNPs in region to file
                     */
                    writeRegionToFile(dragSelectRectangle);
                }
            });
        }
    });
    final MenuItem scmItem3 = new MenuItem("Add To Saved Regions");
    scmItem3.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            /* get coordinates of selection and report back
             * write SNPs in region to file
             */
            saveSelection();
        }
    });
    final MenuItem scmItem4 = new MenuItem("Show/Hide Saved Regions");
    scmItem4.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            /* get coordinates of selection and report back
             * write SNPs in region to file
             */
            hideSavedRegionsMenu.selectedProperty().setValue(!hideSavedRegionsMenu.isSelected());
            hideSavedRegionsMenu.fire();
        }
    });
    final MenuItem scmItem5 = new MenuItem("Zoom Region");
    scmItem5.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    /* get coordinates of selection and report back
                     * write SNPs in region to file
                     */
                    zoomRegion(dragSelectRectangle);
                }
            });
        }
    });
    final MenuItem scmItem6 = new MenuItem("Write Saved Regions to File");
    scmItem6.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    /* get coordinates of selection and report back
                     * write SNPs in region to file
                     */
                    writeSavedRegionsToFile();
                }
            });
        }
    });

    scm.getItems().add(scmItem1);
    scm.getItems().add(scmItem2);
    scm.getItems().add(scmItem3);
    scm.getItems().add(scmItem4);
    scm.getItems().add(scmItem5);
    scm.getItems().add(scmItem6);
    //overlayPane context menu
    ocm = new ContextMenu();
    final MenuItem ocmItem1 = new MenuItem("Save Image to File");
    ocmItem1.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent e) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    drawPaneToPng();
                }
            });
        }
    });

    ocm.getItems().add(ocmItem1);
    ocm.getItems().add(scmItem4);
    ocm.getItems().add(scmItem6);

    //color selections
    colorComponantSelector.getItems().clear();
    colorComponantSelector.getItems().add("AA");
    colorComponantSelector.getItems().add("BB");
    colorComponantSelector.getItems().add("AB");
    colorComponantSelector.getItems().add("Selection Outline");
    colorComponantSelector.getItems().add("Selection Fill");
    colorComponantSelector.getItems().add("Saved Region Outline");
    colorComponantSelector.getItems().add("Saved Region Fill");
    colorComponantSelector.getSelectionModel().selectFirst();
    colorPicker.setValue(colorComponants[0]);
    colorComponantSelector.getSelectionModel().selectedIndexProperty()
            .addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue ov, Number value, Number new_value) {
                    colorPicker.setValue(colorComp.get(new_value.intValue()));
                    colorPicker.fireEvent(new ActionEvent());
                }
            });
    colorPicker.setOnAction(new EventHandler() {
        @Override
        public void handle(Event t) {
            if (!colorComp.get(colorComponantSelector.getSelectionModel().getSelectedIndex())
                    .equals(colorPicker.getValue())) {
                colorComp.set(colorComponantSelector.getSelectionModel().getSelectedIndex(),
                        colorPicker.getValue());
                saveProject();
                //colorComponants[colorComponantSelector.getSelectionModel().getSelectedIndex()] = colorPicker.getValue();
                if (colorComponantSelector.getSelectionModel().getSelectedIndex() == Colors.fill.value) {
                    dragSelectRectangle.setFill(colorPicker.getValue());
                } else if (colorComponantSelector.getSelectionModel().getSelectedIndex() == Colors.line.value) {
                    dragSelectRectangle.setStroke(colorPicker.getValue());
                } else if (colorComponantSelector.getSelectionModel()
                        .getSelectedIndex() == Colors.saveLine.value) {
                    for (Rectangle r : savedRegionsDisplay) {
                        r.setStroke(colorPicker.getValue());
                    }
                } else if (colorComponantSelector.getSelectionModel()
                        .getSelectedIndex() == Colors.saveFill.value) {
                    for (Rectangle r : savedRegionsDisplay) {
                        r.setFill(colorPicker.getValue());
                    }
                } else {
                    removeSavedChromosomeImages();
                    if (redrawCheckBox.isSelected()) {
                        refreshView(null, true);
                    }
                }
            }
        }
    });

    /*perform appropriate action when user selects a chromosome
     * from the chromosome choice box
     */
    chromosomeSelector.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue ov, Number value, Number new_value) {
            chromosomeBoxList = chromosomeSelector.getItems().toArray();

            if (new_value.intValue() > -1) {
                chromosomeSelected((String) chromosomeBoxList[new_value.intValue()]);
            }
        }
    });

    chromosomeSelector.addEventFilter(KeyEvent.ANY, new EventHandler<KeyEvent>() {
        @Override
        public void handle(KeyEvent ke) {
            if (ke.getCode() == KeyCode.UP) {
                ke.consume();
                chromosomeSelector.show();
            }
        }
    });

    selectionOverlayPane.heightProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth,
                Number newSceneWidth) {
            windowResized(new ActionEvent());

        }
    });

    selectionOverlayPane.widthProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth,
                Number newSceneWidth) {
            windowResized(new ActionEvent());
        }
    });

    /*upon addition of a new affected file adjust components accordingly
     * i.e. ensure appropriate chromosomes are in the choice box
     * adjust the split panes to fit all files and redisplay
     */

    affObserve.addListener(new ListChangeListener() {
        @Override
        public void onChanged(ListChangeListener.Change change) {
            change.next();/*from the javadoc 
                          * 'Go to the next change. In initial state is invalid a require 
                          * a call to next() before calling other methods. The first 
                          * next() call will make this object represent the first change.
                          */
            if (change.getRemovedSize() > 0) {
                List<SnpFile> both = new ArrayList<>(unFiles);
                both.addAll(affFiles);
                recheckChromosomeSelector(both);//need to check all files again, not just affFiles
            } else if (change.getAddedSize() > 0) {
                addToChromosomeSelector(affFiles);
            }
        }
    });

    /*as above 
     * but for unaffected files
     */
    unObserve.addListener(new ListChangeListener() {
        @Override
        public void onChanged(ListChangeListener.Change change) {
            change.next();
            if (change.getRemovedSize() > 0) {
                List<SnpFile> both = new ArrayList<>(unFiles);
                both.addAll(affFiles);
                recheckChromosomeSelector(both);//need to check all files again, not just unFiles
            } else if (change.getAddedSize() > 0) {
                addToChromosomeSelector(unFiles);
            }

        }
    });

    selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_MOVED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            if (!genomeVersion.equals("") && chromosomeSelector.getSelectionModel().getSelectedIndex() > -1) {
                try {
                    ChromosomeLength chromLength = new ChromosomeLength(genomeVersion);
                    String currentChrom = (String) chromosomeBoxList[chromosomeSelector.getSelectionModel()
                            .getSelectedIndex()];
                    double coordinate = chromLength.getLength(currentChrom) / chromSplitPane.getWidth()
                            * e.getX();
                    positionIndicator.setText(nf.format(coordinate));

                } catch (Exception ex) {
                    positionIndicator.setText("Build Error!");
                }

            }
        }
    });
    /*handle mouse dragging and effect on dragSelectRectangle
     * 
     */
    dragSelectRectangle.widthProperty().bind(dragSelectRectX.subtract(dragSelectRectInitX));
    dragSelectRectangle.heightProperty().bind(selectionOverlayPane.heightProperty());
    //dragSelectRectangle.strokeProperty().set(colorComponants[Colors.line.value]);
    dragSelectRectangle.setStrokeWidth(4.0);

    //dragSelectRectangle.setBlendMode(BlendMode.SCREEN);
    dragSelectRectangle.setOpacity(0.45);
    dragSelectRectangle.setVisible(false);
    selectionOverlayPane.getChildren().add(dragSelectRectangle);

    selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            if (scm.isShowing()) {
                scm.hide();
            }
            if (!e.isPrimaryButtonDown()) {
                if (e.isSecondaryButtonDown()) {
                    //check we're not overlapping selection
                    if (e.getX() >= dragSelectRectangle.getX()
                            && e.getX() <= (dragSelectRectangle.getX() + dragSelectRectangle.getWidth())) {
                        return;
                    }
                    //check we're not overlapping saved regions
                    for (Rectangle r : savedRegionsDisplay) {
                        if (r.isVisible() && e.getX() >= r.getX() && e.getX() <= r.getX() + r.getWidth()) {
                            return;
                        }
                    }
                    if (chromosomeSelector.getSelectionModel().isEmpty()) {
                        ocmItem1.setDisable(true);
                    } else {
                        ocmItem1.setDisable(false);
                    }
                    ocm.show(selectionOverlayPane, e.getScreenX(), e.getScreenY());

                    return;
                }
            }
            if (ocm.isShowing()) {
                ocm.hide();
            }

            dragSelectRectangle.strokeProperty().set(colorComp.get(Colors.line.value));
            dragSelectRectangle.fillProperty().set(colorComp.get(Colors.fill.value));
            dragSelectRectX.set(0);
            dragSelectRectangle.setVisible(true);
            dragSelectRectangle.setX(e.getX());
            dragSelectRectangle.setY(0);
            dragSelectRectInitX.set(e.getX());
            anchorInitX.set(e.getX());

        }
    });
    selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            if (!e.isPrimaryButtonDown()) {
                return;
            }
            dragSelectRectangle.setVisible(true);
            if (e.getX() > anchorInitX.doubleValue()) {//dragging to the right
                if (e.getX() <= selectionOverlayPane.getLayoutX() + selectionOverlayPane.getWidth()) {
                    //mouse is before the edge of the pane
                    dragSelectRectInitX.set(anchorInitX.doubleValue());
                    dragSelectRectX.set(e.getX());
                } else {
                    //mouse is over the edge
                    dragSelectRectX.set(selectionOverlayPane.getWidth());
                }
            } else {
                if (e.getX() > selectionOverlayPane.getLayoutX()) {
                    dragSelectRectInitX.set(e.getX());
                    dragSelectRectangle.setX(e.getX());
                    dragSelectRectX.set(anchorInitX.doubleValue());
                } else {
                    dragSelectRectInitX.set(0);
                    dragSelectRectangle.setX(0);
                    /* the two lines below are just to trigger 
                    * dragSelectRectangle.widthProperty listener 
                    * so that start coordinate changes to 1
                    */
                    dragSelectRectX.set(anchorInitX.doubleValue() + 1);
                    dragSelectRectX.set(anchorInitX.doubleValue() + 1);

                }
            }
        }
    });

    selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            //dragSelectRectX.set(e.getX());
            if (!e.isPrimaryButtonDown()) {
                return;
            }
            dragSelectRectangle.setVisible(true);
            if (dragSelectRectangle.getWidth() == 0) {
                clearDragSelectRectangle();
            }
        }
    });

    dragSelectRectangle.widthProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observableValue, Object oldValue, Object newRectWidth) {
            if (!genomeVersion.equals("") && chromosomeSelector.getSelectionModel().getSelectedIndex() > -1
                    && dragSelectRectangle.getWidth() > 0) {
                try {
                    ChromosomeLength chromLength = new ChromosomeLength(genomeVersion);
                    String currentChrom = (String) chromosomeBoxList[chromosomeSelector.getSelectionModel()
                            .getSelectedIndex()];
                    double startCoordinate = chromLength.getLength(currentChrom)
                            / selectionOverlayPane.getWidth() * dragSelectRectangle.getX();
                    double selectionWidth = chromLength.getLength(currentChrom)
                            / selectionOverlayPane.getWidth() * dragSelectRectangle.getWidth();
                    if (dragSelectRectangle.getX() == 0) {
                        startCoordinate = 1;
                    }
                    selectionIndicator.setText("chr" + currentChrom + ":" + nf.format(startCoordinate) + "-"
                            + nf.format(startCoordinate + selectionWidth));
                } catch (Exception ex) {
                    selectionIndicator.setText("Build Error!");
                }
            } else {
                selectionIndicator.setText("");
            }

        }
    });

    dragSelectRectangle.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            if (e.getButton() == MouseButton.SECONDARY) {
                if (chromosomeSelector.getSelectionModel().isEmpty()) {
                    scmItem1.setDisable(true);
                    scmItem2.setDisable(true);
                } else {
                    scmItem1.setDisable(false);
                    scmItem2.setDisable(false);
                }
                if (ocm.isShowing()) {
                    ocm.hide();
                }

                scm.show(selectionOverlayPane, e.getScreenX(), e.getScreenY());
            }
        }
    });

}