Example usage for javafx.scene.control MenuItem MenuItem

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

Introduction

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

Prototype

public MenuItem(String text) 

Source Link

Document

Constructs a MenuItem and sets the display text with the specified text

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 ww  .ja  v a  2 s.  c  om
    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:de.pixida.logtest.designer.automaton.AutomatonEdge.java

@Override
ContextMenu createContextMenu() {//  w w  w.  ja va 2 s  .  c om
    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  va2s  . 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:com.QuarkLabs.BTCeClientJavaFX.MainController.java

@FXML
void initialize() {
    assert clearLogButton != null : "fx:id=\"clearLogButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTable != null : "fx:id=\"fundsTable\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert logField != null : "fx:id=\"logField\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert buyButton != null : "fx:id=\"buyButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert sellButton != null : "fx:id=\"sellButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert showActiveOrdersButton != null : "fx:id=\"showActiveOrdersButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableLastColumn != null : "fx:id=\"tickerTableLastColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTablePairColumn != null : "fx:id=\"tickerTablePairColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTable != null : "fx:id=\"tickersTable\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableBuyColumn != null : "fx:id=\"tickersTableBuyColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableFeeColumn != null : "fx:id=\"tickersTableFeeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tickersTableSellColumn != null : "fx:id=\"tickersTableSellColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradeAmountValue != null : "fx:id=\"tradeAmountValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradePriceCurrencyType != null : "fx:id=\"tradeCurrencyPriceValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradeCurrencyType != null : "fx:id=\"tradeCurrencyType\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert tradePriceValue != null : "fx:id=\"tradePriceValue\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert updateFundsButton != null : "fx:id=\"updateFundsButton\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTableCurrencyColumn != null : "fx:id=\"fundsTableCurrencyColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert fundsTableValueColumn != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTable != null : "fx:id=\"fundsTableValueColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersAmountColumn != null : "fx:id=\"activeOrdersAmountColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersPairColumn != null : "fx:id=\"activeOrdersPairColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersRateColumn != null : "fx:id=\"activeOrdersRateColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTimeColumn != null : "fx:id=\"activeOrdersTimeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersTypeColumn != null : "fx:id=\"activeOrdersTypeColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";
    assert activeOrdersCancelColumn != null : "fx:id=\"activeOrdersCancelColumn\" was not injected: check your FXML file 'mainlayout.fxml'.";

    //Holder for all main API methods of exchange
    app = new App();

    //Loading configs
    loadExchangeConfig();//from   w  ww. j ava2 s. c  om

    //Populate choiceboxes at the trading section
    tradeCurrencyType.setItems(FXCollections.observableArrayList(currencies));
    tradeCurrencyType.setValue(currencies.get(0));
    tradePriceCurrencyType.setItems(FXCollections.observableArrayList(currencies));
    tradePriceCurrencyType.setValue(currencies.get(0));

    //Active Orders table
    activeOrdersAmountColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("amount"));
    activeOrdersPairColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("pair"));
    activeOrdersRateColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, Double>("rate"));
    activeOrdersTimeColumn.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<ActiveOrder, String>, ObservableValue<String>>() {
                @Override
                public ObservableValue<String> call(
                        TableColumn.CellDataFeatures<ActiveOrder, String> activeOrderStringCellDataFeatures) {
                    ActiveOrder activeOrder = activeOrderStringCellDataFeatures.getValue();
                    DateFormat dateFormat = DateFormat.getDateTimeInstance();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(activeOrder.getTimestamp() * 1000);
                    return new SimpleStringProperty(dateFormat.format(calendar.getTime()));
                }
            });
    activeOrdersTypeColumn.setCellValueFactory(new PropertyValueFactory<ActiveOrder, String>("type"));
    activeOrdersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    activeOrdersCancelColumn
            .setCellFactory(new Callback<TableColumn<ActiveOrder, Boolean>, TableCell<ActiveOrder, Boolean>>() {
                @Override
                public TableCell<ActiveOrder, Boolean> call(
                        TableColumn<ActiveOrder, Boolean> activeOrderBooleanTableColumn) {
                    return new ButtonCell<>(activeOrdersTable);
                }
            });
    activeOrdersCancelColumn.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<ActiveOrder, Boolean>, ObservableValue<Boolean>>() {
                @Override
                public ObservableValue<Boolean> call(
                        TableColumn.CellDataFeatures<ActiveOrder, Boolean> activeOrderBooleanCellDataFeatures) {
                    return new SimpleBooleanProperty(true);
                }
            });

    //Tickers Table
    MenuItem showOrdersBook = new MenuItem("Show Orders Book");
    MenuItem showPublicTrades = new MenuItem("Show Public Trades");

    ContextMenu contextMenu = new ContextMenu(showOrdersBook, showPublicTrades);

    tickersTable.setItems(tickers);
    tickersTable.setContextMenu(contextMenu);
    tickersTableBuyColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("buy"));
    tickersTableFeeColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("fee"));
    tickersTableSellColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("sell"));
    tickersTableLastColumn.setCellValueFactory(new PropertyValueFactory<Ticker, Double>("last"));
    tickersTablePairColumn.setCellValueFactory(new PropertyValueFactory<Ticker, String>("pair"));
    tickersTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    tickersTable.setRowFactory(new Callback<TableView<Ticker>, TableRow<Ticker>>() {
        @Override
        public TableRow<Ticker> call(TableView<Ticker> tickerTableView) {
            return new TableRow<Ticker>() {
                @Override
                protected void updateItem(Ticker ticker, boolean b) {
                    super.updateItem(ticker, b);
                    if (!b) {
                        if (tickersData.containsKey(ticker.getPair())) {
                            if (ticker.getLast() < tickersData.get(ticker.getPair()).getLast()) {
                                setStyle("-fx-control-inner-background: rgba(186, 0, 0, 0.5);");
                            } else if (ticker.getLast() == tickersData.get(ticker.getPair()).getLast()) {
                                setStyle("-fx-control-inner-background: rgba(215, 193, 44, 0.5);");
                            } else {
                                setStyle("-fx-control-inner-background: rgba(0, 147, 0, 0.5);");
                            }
                        }
                    }
                }
            };
        }
    });

    //Menu item to show Orders Book
    showOrdersBook.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem();
            Parent root;
            try {
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_ORDERS_BOOK_LAYOUT),
                        resources);
                root = (Parent) fxmlLoader.load();
                OrdersBookController ordersBookController = fxmlLoader.getController();
                ordersBookController.injectPair(selectedTicker.getPair());
                Stage stage = new Stage();
                stage.setTitle("Orders Book for " + selectedTicker.getPair().replace("_", "/").toUpperCase());
                stage.setScene(new Scene(root));
                stage.setResizable(false);
                stage.show();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    //Menu item to show Public Trades
    showPublicTrades.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            Ticker selectedTicker = tickersTable.getSelectionModel().getSelectedItem();
            Parent root;
            try {
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(PATH_TO_TRADES_LAYOUT),
                        resources);
                root = (Parent) fxmlLoader.load();
                PublicTradesController publicTradesController = fxmlLoader.getController();
                publicTradesController.injectPair(selectedTicker.getPair());
                Stage stage = new Stage();
                stage.setTitle("Public Trades for " + selectedTicker.getPair().replace("_", "/").toUpperCase());
                stage.setScene(new Scene(root));
                stage.setResizable(false);
                stage.show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    //Funds Table
    fundsTableCurrencyColumn.setCellValueFactory(new PropertyValueFactory<Fund, String>("currency"));
    fundsTableValueColumn.setCellValueFactory(new PropertyValueFactory<Fund, Double>("value"));
    fundsTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    fundsTable.setItems(fundsData);

    //Task to load tickers data from server
    final javafx.concurrent.Service loadTickersService = new javafx.concurrent.Service() {
        @Override
        protected Task createTask() {
            Task<JSONObject> loadTickers = new Task<JSONObject>() {
                @Override
                protected JSONObject call() throws Exception {
                    String[] pairsArray = new String[pairs.size()];
                    pairsArray = pairs.toArray(pairsArray);
                    return App.getPairInfo(pairsArray);
                }
            };

            loadTickers.setOnFailed(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent workerStateEvent) {
                    logField.appendText(workerStateEvent.getSource().getException().getMessage() + "\r\n");
                }
            });

            loadTickers.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                @Override
                public void handle(WorkerStateEvent workerStateEvent) {
                    JSONObject jsonObject = (JSONObject) workerStateEvent.getSource().getValue();

                    //ugly hack to store old values
                    //dump old values to tickersData
                    //TODO think about better solution
                    if (tickers.size() != 0) {
                        for (Ticker x : tickers) {
                            tickersData.put(x.getPair(), x);
                        }
                    }
                    tickers.clear();
                    for (Iterator iterator = jsonObject.keys(); iterator.hasNext();) {
                        String key = (String) iterator.next();
                        JSONObject data = jsonObject.getJSONObject(key);
                        Ticker ticker = new Ticker();
                        ticker.setPair(key);
                        ticker.setUpdated(data.optLong("updated"));
                        ticker.setAvg(data.optDouble("avg"));
                        ticker.setBuy(data.optDouble("buy"));
                        ticker.setSell(data.optDouble("sell"));
                        ticker.setHigh(data.optDouble("high"));
                        ticker.setLast(data.optDouble("last"));
                        ticker.setLow(data.optDouble("low"));
                        ticker.setVol(data.optDouble("vol"));
                        ticker.setVolCur(data.optDouble("vol_cur"));
                        tickers.add(ticker);
                    }

                }
            });
            return loadTickers;
        }
    };

    //Update tickers every 15 seconds
    //TODO better solution is required
    Timeline timeline = new Timeline(new KeyFrame(Duration.ZERO, new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            loadTickersService.restart();
        }
    }), new KeyFrame(Duration.seconds(15)));
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.playFromStart();

}

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   ww w. j  a v a 2 s. co  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.neuronrobotics.bowlerstudio.MainController.java

private void setToLoggedIn(final String name) {
    // new Exception().printStackTrace();
    FxTimer.runLater(Duration.ofMillis(100), () -> {
        logoutGithub.disableProperty().set(false);
        logoutGithub.setText("Log out " + name);
        new Thread() {
            public void run() {

                GitHub github = ScriptingEngine.getGithub();
                while (github == null) {
                    github = ScriptingEngine.getGithub();
                    ThreadUtil.wait(20);
                }/* w  w w.  j a  va  2  s .  co m*/
                try {
                    GHMyself myself = github.getMyself();
                    PagedIterable<GHGist> gists = myself.listGists();
                    Platform.runLater(() -> {
                        myGists.getItems().clear();
                    });
                    ThreadUtil.wait(20);
                    for (GHGist gist : gists) {
                        String desc = gist.getDescription();
                        if (desc == null || desc.length() == 0) {
                            desc = gist.getFiles().keySet().toArray()[0].toString();
                        }
                        Menu tmpGist = new Menu(desc);

                        MenuItem loadWebGist = new MenuItem("Show Web Gist...");
                        loadWebGist.setOnAction(event -> {
                            String webURL = gist.getHtmlUrl();
                            try {
                                BowlerStudio.openUrlInNewTab(new URL(webURL));
                            } catch (MalformedURLException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        });
                        MenuItem addFile = new MenuItem("Add file to Gist...");
                        addFile.setOnAction(event -> {
                            new Thread() {
                                public void run() {

                                }
                            }.start();
                        });
                        Platform.runLater(() -> {
                            tmpGist.getItems().addAll(addFile, loadWebGist);
                        });
                        EventHandler<Event> loadFiles = new EventHandler<Event>() {
                            @Override
                            public void handle(Event ev) {

                                // for(ScriptingEngine.)
                                new Thread() {
                                    public void run() {
                                        System.out.println("Loading files");
                                        ArrayList<String> listofFiles = ScriptingEngine
                                                .filesInGit(gist.getGitPushUrl(), "master", null);
                                        for (String s : listofFiles) {
                                            MenuItem tmp = new MenuItem(s);
                                            tmp.setOnAction(event -> {
                                                new Thread() {
                                                    public void run() {
                                                        try {
                                                            File fileSelected = ScriptingEngine
                                                                    .fileFromGit(gist.getGitPushUrl(), s);
                                                            BowlerStudio.createFileTab(fileSelected);
                                                        } catch (Exception e) {
                                                            // TODO
                                                            // Auto-generated
                                                            // catch block
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                }.start();

                                            });
                                            Platform.runLater(() -> {
                                                tmpGist.getItems().add(tmp);
                                                tmpGist.setOnShowing(null);

                                            });
                                        }
                                        Platform.runLater(() -> {
                                            tmpGist.hide();
                                            Platform.runLater(() -> {
                                                tmpGist.show();
                                            });
                                        });
                                    }
                                }.start();
                            }
                        };

                        tmpGist.setOnShowing(loadFiles);
                        Platform.runLater(() -> {
                            myGists.getItems().add(tmpGist);
                        });

                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();

    });
}

From source file:qupath.lib.gui.tma.TMASummaryViewer.java

private void initialize() {

    model = new TMATableModel();

    groupByIDProperty.addListener((v, o, n) -> refreshTableData());

    MenuBar menuBar = new MenuBar();
    Menu menuFile = new Menu("File");
    MenuItem miOpen = new MenuItem("Open...");
    miOpen.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN));
    miOpen.setOnAction(e -> {/*from   w w w. j  av a 2s  .c  o  m*/
        File file = QuPathGUI.getDialogHelper(stage).promptForFile(null, null, "TMA data files",
                new String[] { "qptma" });
        if (file == null)
            return;
        setInputFile(file);
    });

    MenuItem miSave = new MenuItem("Save As...");
    miSave.setAccelerator(
            new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    miSave.setOnAction(
            e -> SummaryMeasurementTableCommand.saveTableModel(model, null, Collections.emptyList()));

    MenuItem miImportFromImage = new MenuItem("Import from current image...");
    miImportFromImage.setAccelerator(
            new KeyCodeCombination(KeyCode.I, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    miImportFromImage.setOnAction(e -> setTMAEntriesFromOpenImage());

    MenuItem miImportFromProject = new MenuItem("Import from current project... (experimental)");
    miImportFromProject.setAccelerator(
            new KeyCodeCombination(KeyCode.P, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN));
    miImportFromProject.setOnAction(e -> setTMAEntriesFromOpenProject());

    MenuItem miImportClipboard = new MenuItem("Import from clipboard...");
    miImportClipboard.setOnAction(e -> {
        String text = Clipboard.getSystemClipboard().getString();
        if (text == null) {
            DisplayHelpers.showErrorMessage("Import scores", "Clipboard is empty!");
            return;
        }
        int n = importScores(text);
        if (n > 0) {
            setTMAEntries(new ArrayList<>(entriesBase));
        }
        DisplayHelpers.showMessageDialog("Import scores", "Number of scores imported: " + n);
    });

    Menu menuEdit = new Menu("Edit");
    MenuItem miCopy = new MenuItem("Copy table to clipboard");
    miCopy.setOnAction(e -> {
        SummaryMeasurementTableCommand.copyTableContentsToClipboard(model, Collections.emptyList());
    });

    combinedPredicate.addListener((v, o, n) -> {
        // We want any other changes triggered by this to have happened, 
        // so that the data has already been updated
        Platform.runLater(() -> handleTableContentChange());
    });

    // Reset the scores for missing cores - this ensures they will be NaN and not influence subsequent results
    MenuItem miResetMissingScores = new MenuItem("Reset scores for missing cores");
    miResetMissingScores.setOnAction(e -> {
        int changes = 0;
        for (TMAEntry entry : entriesBase) {
            if (!entry.isMissing())
                continue;
            boolean changed = false;
            for (String m : entry.getMeasurementNames().toArray(new String[0])) {
                if (!TMASummaryEntry.isSurvivalColumn(m) && !Double.isNaN(entry.getMeasurementAsDouble(m))) {
                    entry.putMeasurement(m, null);
                    changed = true;
                }
            }
            if (changed)
                changes++;
        }
        if (changes == 0) {
            logger.info("No changes made when resetting scores for missing cores!");
            return;
        }
        logger.info("{} change(s) made when resetting scores for missing cores!", changes);
        table.refresh();
        updateSurvivalCurves();
        if (scatterPane != null)
            scatterPane.updateChart();
        if (histogramDisplay != null)
            histogramDisplay.refreshHistogram();
    });
    menuEdit.getItems().add(miResetMissingScores);

    QuPathGUI.addMenuItems(menuFile, miOpen, miSave, null, miImportClipboard, null, miImportFromImage,
            miImportFromProject);
    menuBar.getMenus().add(menuFile);
    menuEdit.getItems().add(miCopy);
    menuBar.getMenus().add(menuEdit);

    menuFile.setOnShowing(e -> {
        boolean imageDataAvailable = QuPathGUI.getInstance() != null
                && QuPathGUI.getInstance().getImageData() != null
                && QuPathGUI.getInstance().getImageData().getHierarchy().getTMAGrid() != null;
        miImportFromImage.setDisable(!imageDataAvailable);
        boolean projectAvailable = QuPathGUI.getInstance() != null
                && QuPathGUI.getInstance().getProject() != null
                && !QuPathGUI.getInstance().getProject().getImageList().isEmpty();
        miImportFromProject.setDisable(!projectAvailable);
    });

    // Double-clicking previously used for comments... but conflicts with tree table expansion
    //      table.setOnMouseClicked(e -> {
    //         if (!e.isPopupTrigger() && e.getClickCount() > 1)
    //            promptForComment();
    //      });

    table.setPlaceholder(new Text("Drag TMA data folder onto window, or choose File -> Open"));
    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    BorderPane pane = new BorderPane();
    pane.setTop(menuBar);
    menuBar.setUseSystemMenuBar(true);

    // Create options
    ToolBar toolbar = new ToolBar();
    Label labelMeasurementMethod = new Label("Combination method");
    labelMeasurementMethod.setLabelFor(comboMeasurementMethod);
    labelMeasurementMethod
            .setTooltip(new Tooltip("Method whereby measurements for multiple cores with the same "
                    + TMACoreObject.KEY_UNIQUE_ID + " will be combined"));

    CheckBox cbHidePane = new CheckBox("Hide pane");
    cbHidePane.setSelected(hidePaneProperty.get());
    cbHidePane.selectedProperty().bindBidirectional(hidePaneProperty);

    CheckBox cbGroupByID = new CheckBox("Group by ID");
    entriesBase.addListener((Change<? extends TMAEntry> event) -> {
        if (!event.getList().stream().anyMatch(e -> e.getMetadataValue(TMACoreObject.KEY_UNIQUE_ID) != null)) {
            cbGroupByID.setSelected(false);
            cbGroupByID.setDisable(true);
        } else {
            cbGroupByID.setDisable(false);
        }
    });
    cbGroupByID.setSelected(groupByIDProperty.get());
    cbGroupByID.selectedProperty().bindBidirectional(groupByIDProperty);

    CheckBox cbUseSelected = new CheckBox("Use selection only");
    cbUseSelected.selectedProperty().bindBidirectional(useSelectedProperty);

    CheckBox cbSkipMissing = new CheckBox("Hide missing cores");
    cbSkipMissing.selectedProperty().bindBidirectional(skipMissingCoresProperty);
    skipMissingCoresProperty.addListener((v, o, n) -> {
        table.refresh();
        updateSurvivalCurves();
        if (histogramDisplay != null)
            histogramDisplay.refreshHistogram();
        updateSurvivalCurves();
        if (scatterPane != null)
            scatterPane.updateChart();
    });

    toolbar.getItems().addAll(labelMeasurementMethod, comboMeasurementMethod,
            new Separator(Orientation.VERTICAL), cbHidePane, new Separator(Orientation.VERTICAL), cbGroupByID,
            new Separator(Orientation.VERTICAL), cbUseSelected, new Separator(Orientation.VERTICAL),
            cbSkipMissing);
    comboMeasurementMethod.getItems().addAll(MeasurementCombinationMethod.values());
    comboMeasurementMethod.getSelectionModel().select(MeasurementCombinationMethod.MEDIAN);
    selectedMeasurementCombinationProperty.addListener((v, o, n) -> table.refresh());

    ContextMenu popup = new ContextMenu();
    MenuItem miSetMissing = new MenuItem("Set missing");
    miSetMissing.setOnAction(e -> setSelectedMissingStatus(true));

    MenuItem miSetAvailable = new MenuItem("Set available");
    miSetAvailable.setOnAction(e -> setSelectedMissingStatus(false));

    MenuItem miExpand = new MenuItem("Expand all");
    miExpand.setOnAction(e -> {
        if (table.getRoot() == null)
            return;
        for (TreeItem<?> item : table.getRoot().getChildren()) {
            item.setExpanded(true);
        }
    });
    MenuItem miCollapse = new MenuItem("Collapse all");
    miCollapse.setOnAction(e -> {
        if (table.getRoot() == null)
            return;
        for (TreeItem<?> item : table.getRoot().getChildren()) {
            item.setExpanded(false);
        }
    });
    popup.getItems().addAll(miSetMissing, miSetAvailable, new SeparatorMenuItem(), miExpand, miCollapse);
    table.setContextMenu(popup);

    table.setRowFactory(e -> {
        TreeTableRow<TMAEntry> row = new TreeTableRow<>();

        //         // Make rows invisible if they don't pass the predicate
        //         row.visibleProperty().bind(Bindings.createBooleanBinding(() -> {
        //               TMAEntry entry = row.getItem();
        //               if (entry == null || (entry.isMissing() && skipMissingCoresProperty.get()))
        //                     return false;
        //               return entries.getPredicate() == null || entries.getPredicate().test(entry);
        //               },
        //               skipMissingCoresProperty,
        //               entries.predicateProperty()));

        // Style rows according to what they contain
        row.styleProperty().bind(Bindings.createStringBinding(() -> {
            if (row.isSelected())
                return "";
            TMAEntry entry = row.getItem();
            if (entry == null || entry instanceof TMASummaryEntry)
                return "";
            else if (entry.isMissing())
                return "-fx-background-color:rgb(225,225,232)";
            else
                return "-fx-background-color:rgb(240,240,245)";
        }, row.itemProperty(), row.selectedProperty()));
        //         row.itemProperty().addListener((v, o, n) -> {
        //            if (n == null || n instanceof TMASummaryEntry || row.isSelected())
        //               row.setStyle("");
        //            else if (n.isMissing())
        //               row.setStyle("-fx-background-color:rgb(225,225,232)");            
        //            else
        //               row.setStyle("-fx-background-color:rgb(240,240,245)");            
        //         });
        return row;
    });

    BorderPane paneTable = new BorderPane();
    paneTable.setTop(toolbar);
    paneTable.setCenter(table);

    MasterDetailPane mdTablePane = new MasterDetailPane(Side.RIGHT, paneTable, createSidePane(), true);

    mdTablePane.showDetailNodeProperty().bind(Bindings.createBooleanBinding(
            () -> !hidePaneProperty.get() && !entriesBase.isEmpty(), hidePaneProperty, entriesBase));
    mdTablePane.setDividerPosition(2.0 / 3.0);

    pane.setCenter(mdTablePane);

    model.getEntries().addListener(new ListChangeListener<TMAEntry>() {
        @Override
        public void onChanged(ListChangeListener.Change<? extends TMAEntry> c) {
            if (histogramDisplay != null)
                histogramDisplay.refreshHistogram();
            updateSurvivalCurves();
            if (scatterPane != null)
                scatterPane.updateChart();
        }
    });

    Label labelPredicate = new Label();
    labelPredicate.setPadding(new Insets(5, 5, 5, 5));
    labelPredicate.setAlignment(Pos.CENTER);
    //      labelPredicate.setStyle("-fx-background-color: rgba(20, 120, 20, 0.15);");
    labelPredicate.setStyle("-fx-background-color: rgba(120, 20, 20, 0.15);");

    labelPredicate.textProperty().addListener((v, o, n) -> {
        if (n.trim().length() > 0)
            pane.setBottom(labelPredicate);
        else
            pane.setBottom(null);
    });
    labelPredicate.setMaxWidth(Double.MAX_VALUE);
    labelPredicate.setMaxHeight(labelPredicate.getPrefHeight());
    labelPredicate.setTextAlignment(TextAlignment.CENTER);
    predicateMeasurements.addListener((v, o, n) -> {
        if (n == null)
            labelPredicate.setText("");
        else if (n instanceof TablePredicate) {
            TablePredicate tp = (TablePredicate) n;
            if (tp.getOriginalCommand().trim().isEmpty())
                labelPredicate.setText("");
            else
                labelPredicate.setText("Predicate: " + tp.getOriginalCommand());
        } else
            labelPredicate.setText("Predicate: " + n.toString());
    });
    //      predicate.set(new TablePredicate("\"Tumor\" > 100"));

    scene = new Scene(pane);

    scene.addEventHandler(KeyEvent.KEY_PRESSED, e -> {
        KeyCode code = e.getCode();
        if ((code == KeyCode.SPACE || code == KeyCode.ENTER) && entrySelected != null) {
            promptForComment();
            return;
        }
    });

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private void setupTableWithChanges(TableView<Change> tv, Dataset tp) {
    tv.setEditable(true);//w w  w  .java2 s . 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");
}