Example usage for javafx.scene.control Menu getItems

List of usage examples for javafx.scene.control Menu getItems

Introduction

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

Prototype

public final ObservableList<MenuItem> getItems() 

Source Link

Document

The items to show within this menu.

Usage

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @param primaryStage//from   w  ww .  ja v  a  2 s  .c  om
 * @param racine
 * @param taille
 * @throws Exception
 */
private void creeMenu(VBox racine, int taille) throws Exception {
    //Pane myPane = (Pane) FXMLLoader.load(getClass().getResource("menuPrincipal.fxml"));
    VBox myPane = new VBox();
    myPane.setPrefHeight(80);
    myPane.setPrefWidth(3000);
    MenuBar menuPrincipal = new MenuBar();
    menuPrincipal.setMinHeight(25);
    menuPrincipal.setPrefHeight(29);
    menuPrincipal.setPrefWidth(3000);
    /* 
     Menu projets
     */
    Menu menuProjet = new Menu(rb.getString("projets"));
    menuPrincipal.getMenus().add(menuProjet);
    nouveauProjet = new MenuItem(rb.getString("nouveauProjet"));
    nouveauProjet.setAccelerator(KeyCombination.keyCombination("Ctrl+N"));
    menuProjet.getItems().add(nouveauProjet);
    chargeProjet = new MenuItem(rb.getString("ouvrirProjet"));
    chargeProjet.setAccelerator(KeyCombination.keyCombination("Ctrl+O"));
    menuProjet.getItems().add(chargeProjet);
    sauveProjet = new MenuItem(rb.getString("sauverProjet"));
    sauveProjet.setDisable(true);
    sauveProjet.setAccelerator(KeyCombination.keyCombination("Ctrl+S"));
    menuProjet.getItems().add(sauveProjet);
    sauveSousProjet = new MenuItem(rb.getString("sauverProjetSous"));
    sauveSousProjet.setDisable(true);
    sauveSousProjet.setAccelerator(KeyCombination.keyCombination("Shift+Ctrl+S"));
    menuProjet.getItems().add(sauveSousProjet);
    derniersProjets = new Menu(rb.getString("derniersProjets"));
    //        derniersProjets.setDisable(true);
    menuProjet.getItems().add(derniersProjets);
    fichHistoFichiers = new File(repertConfig.getAbsolutePath() + File.separator + "derniersprojets.cfg");
    nombreHistoFichiers = 0;
    if (fichHistoFichiers.exists()) {
        FileReader fr;
        fr = new FileReader(fichHistoFichiers);
        try (BufferedReader br = new BufferedReader(fr)) {
            while ((texteHisto = br.readLine()) != null) {
                MenuItem menuDerniersFichiers = new MenuItem(texteHisto);
                derniersProjets.getItems().add(menuDerniersFichiers);
                histoFichiers[nombreHistoFichiers] = texteHisto;
                nombreHistoFichiers++;
                menuDerniersFichiers.setOnAction((ActionEvent e) -> {
                    MenuItem mnu = (MenuItem) e.getSource();
                    try {
                        try {
                            projetChargeNom(mnu.getText());
                        } catch (InterruptedException ex) {
                            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                    }
                });

            }
        }
    }

    SeparatorMenuItem sep1 = new SeparatorMenuItem();
    menuProjet.getItems().add(sep1);
    fermerProjet = new MenuItem(rb.getString("quitterApplication"));
    fermerProjet.setAccelerator(KeyCombination.keyCombination("Ctrl+Q"));
    menuProjet.getItems().add(fermerProjet);
    /*
     Menu affichage
     */
    Menu menuAffichage = new Menu(rb.getString("affichage"));
    menuPrincipal.getMenus().add(menuAffichage);
    affichageVisite = new MenuItem(rb.getString("main.creationVisite"));
    affichageVisite.setAccelerator(KeyCombination.keyCombination("Ctrl+1"));
    menuAffichage.getItems().add(affichageVisite);
    affichageInterface = new MenuItem(rb.getString("main.creationInterface"));
    affichageInterface.setAccelerator(KeyCombination.keyCombination("Ctrl+2"));
    menuAffichage.getItems().add(affichageInterface);
    affichagePlan = new MenuItem(rb.getString("main.tabPlan"));
    affichagePlan.setAccelerator(KeyCombination.keyCombination("Ctrl+3"));
    affichagePlan.setDisable(true);
    menuAffichage.getItems().add(affichagePlan);
    SeparatorMenuItem sep3 = new SeparatorMenuItem();
    menuAffichage.getItems().add(sep3);
    configTransformation = new MenuItem(rb.getString("affichageConfiguration"));
    menuAffichage.getItems().add(configTransformation);

    /*
     Menu panoramiques
     */
    menuPanoramique = new Menu(rb.getString("panoramiques"));
    menuPanoramique.setDisable(true);
    menuPrincipal.getMenus().add(menuPanoramique);
    ajouterPano = new MenuItem(rb.getString("ajouterPanoramiques"));
    ajouterPano.setAccelerator(KeyCombination.keyCombination("Ctrl+A"));
    menuPanoramique.getItems().add(ajouterPano);
    ajouterPlan = new MenuItem(rb.getString("ajouterPlan"));
    ajouterPlan.setAccelerator(KeyCombination.keyCombination("Ctrl+P"));
    menuPanoramique.getItems().add(ajouterPlan);
    ajouterPlan.setDisable(true);
    SeparatorMenuItem sep2 = new SeparatorMenuItem();
    menuPanoramique.getItems().add(sep2);
    visiteGenere = new MenuItem(rb.getString("genererVisite"));
    visiteGenere.setDisable(true);
    visiteGenere.setAccelerator(KeyCombination.keyCombination("Ctrl+V"));
    menuPanoramique.getItems().add(visiteGenere);
    /*
     Menu Modles 
     */
    menuModeles = new Menu(rb.getString("menuModele"));
    menuPrincipal.getMenus().add(menuModeles);

    chargerModele = new MenuItem(rb.getString("modeleCharger"));
    menuModeles.getItems().add(chargerModele);

    sauverModele = new MenuItem(rb.getString("modeleSauver"));
    menuModeles.getItems().add(sauverModele);

    /*
     Menu transformations 
     */
    menuTransformation = new Menu(rb.getString("outils"));
    menuPrincipal.getMenus().add(menuTransformation);
    equi2CubeTransformation = new MenuItem(rb.getString("outilsEqui2Cube"));
    menuTransformation.getItems().add(equi2CubeTransformation);
    cube2EquiTransformation = new MenuItem(rb.getString("outilsCube2Equi"));
    menuTransformation.getItems().add(cube2EquiTransformation);

    /*
     Menu Aide
     */
    Menu menuAide = new Menu(rb.getString("aide"));
    menuPrincipal.getMenus().add(menuAide);
    aide = new MenuItem(rb.getString("aideAide"));
    aide.setAccelerator(KeyCombination.keyCombination("Ctrl+H"));
    menuAide.getItems().add(aide);
    SeparatorMenuItem sep4 = new SeparatorMenuItem();
    menuAide.getItems().add(sep4);
    aPropos = new MenuItem(rb.getString("aideAPropos"));
    menuAide.getItems().add(aPropos);
    /*
     barre de boutons 
     */
    HBox barreBouton = new HBox();
    barreBouton.getStyleClass().add("menuBarreOutils1");

    barreBouton.setPrefHeight(50);
    barreBouton.setMinHeight(50);
    barreBouton.setPrefWidth(3000);
    /*
     Bouton nouveau Projet
     */
    ScrollPane spBtnNouvprojet = new ScrollPane();
    spBtnNouvprojet.getStyleClass().add("menuBarreOutils");
    spBtnNouvprojet.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnNouvprojet.setPrefHeight(35);
    spBtnNouvprojet.setMaxHeight(35);
    spBtnNouvprojet.setPadding(new Insets(2));
    spBtnNouvprojet.setPrefWidth(35);

    HBox.setMargin(spBtnNouvprojet, new Insets(5, 15, 0, 15));
    imgNouveauProjet = new ImageView(
            new Image("file:" + repertAppli + File.separator + "images/nouveauProjet.png"));
    spBtnNouvprojet.setContent(imgNouveauProjet);
    Tooltip t0 = new Tooltip(rb.getString("nouveauProjet"));
    t0.setStyle(tooltipStyle);
    spBtnNouvprojet.setTooltip(t0);
    barreBouton.getChildren().add(spBtnNouvprojet);
    /*
     Bouton ouvrir Projet
     */
    ScrollPane spBtnOuvrirProjet = new ScrollPane();
    spBtnOuvrirProjet.getStyleClass().add("menuBarreOutils");
    spBtnOuvrirProjet.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnOuvrirProjet.setPrefHeight(35);
    spBtnOuvrirProjet.setMaxHeight(35);
    spBtnOuvrirProjet.setPadding(new Insets(2));
    spBtnOuvrirProjet.setPrefWidth(35);

    HBox.setMargin(spBtnOuvrirProjet, new Insets(5, 15, 0, 0));
    imgChargeProjet = new ImageView(
            new Image("file:" + repertAppli + File.separator + "images/ouvrirProjet.png"));
    spBtnOuvrirProjet.setContent(imgChargeProjet);
    Tooltip t1 = new Tooltip(rb.getString("ouvrirProjet"));
    t1.setStyle(tooltipStyle);
    spBtnOuvrirProjet.setTooltip(t1);
    barreBouton.getChildren().add(spBtnOuvrirProjet);

    /*
     Bouton sauve Projet
     */
    ScrollPane spBtnSauveProjet = new ScrollPane();
    spBtnSauveProjet.getStyleClass().add("menuBarreOutils");
    spBtnSauveProjet.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnSauveProjet.setPrefHeight(35);
    spBtnSauveProjet.setMaxHeight(35);
    spBtnSauveProjet.setPadding(new Insets(2));
    spBtnSauveProjet.setPrefWidth(35);

    HBox.setMargin(spBtnSauveProjet, new Insets(5, 15, 0, 0));
    imgSauveProjet = new ImageView(
            new Image("file:" + repertAppli + File.separator + "images/sauveProjet.png"));
    spBtnSauveProjet.setContent(imgSauveProjet);
    Tooltip t2 = new Tooltip(rb.getString("sauverProjet"));
    t2.setStyle(tooltipStyle);
    spBtnSauveProjet.setTooltip(t2);
    barreBouton.getChildren().add(spBtnSauveProjet);
    Separator sepImages = new Separator(Orientation.VERTICAL);
    sepImages.prefHeight(200);
    barreBouton.getChildren().add(sepImages);
    imgSauveProjet.setDisable(true);
    imgSauveProjet.setOpacity(0.3);
    /*
     Bouton Ajoute Panoramique
     */
    ScrollPane spBtnAjoutePano = new ScrollPane();
    spBtnAjoutePano.getStyleClass().add("menuBarreOutils");
    spBtnAjoutePano.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnAjoutePano.setPrefHeight(35);
    spBtnAjoutePano.setMaxHeight(35);
    spBtnAjoutePano.setPadding(new Insets(2));
    spBtnAjoutePano.setPrefWidth(35);

    HBox.setMargin(spBtnAjoutePano, new Insets(5, 15, 0, 15));
    imgAjouterPano = new ImageView(
            new Image("file:" + repertAppli + File.separator + "images/ajoutePanoramique.png"));
    spBtnAjoutePano.setContent(imgAjouterPano);
    Tooltip t3 = new Tooltip(rb.getString("ajouterPanoramiques"));
    t3.setStyle(tooltipStyle);
    spBtnAjoutePano.setTooltip(t3);
    barreBouton.getChildren().add(spBtnAjoutePano);
    imgAjouterPano.setDisable(true);
    imgAjouterPano.setOpacity(0.3);

    /*
     Bouton Ajoute Panoramique
     */
    ScrollPane spBtnAjoutePlan = new ScrollPane();
    spBtnAjoutePlan.getStyleClass().add("menuBarreOutils");
    spBtnAjoutePlan.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnAjoutePlan.setPrefHeight(35);
    spBtnAjoutePlan.setMaxHeight(35);
    spBtnAjoutePlan.setPadding(new Insets(2));
    spBtnAjoutePlan.setPrefWidth(35);

    HBox.setMargin(spBtnAjoutePlan, new Insets(5, 15, 0, 15));
    imgAjouterPlan = new ImageView(new Image("file:" + repertAppli + File.separator + "images/ajoutePlan.png"));
    spBtnAjoutePlan.setContent(imgAjouterPlan);
    Tooltip t31 = new Tooltip(rb.getString("ajouterPlan"));
    t31.setStyle(tooltipStyle);
    spBtnAjoutePlan.setTooltip(t31);
    barreBouton.getChildren().add(spBtnAjoutePlan);
    imgAjouterPlan.setDisable(true);
    imgAjouterPlan.setOpacity(0.3);

    /*
     Bouton Gnre
     */
    ScrollPane spBtnGenereVisite = new ScrollPane();
    spBtnGenereVisite.getStyleClass().add("menuBarreOutils");
    spBtnGenereVisite.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnGenereVisite.setPrefHeight(35);
    spBtnGenereVisite.setMaxHeight(35);
    spBtnGenereVisite.setPadding(new Insets(2));
    spBtnGenereVisite.setPrefWidth(70);

    HBox.setMargin(spBtnGenereVisite, new Insets(5, 15, 0, 0));
    imgVisiteGenere = new ImageView(
            new Image("file:" + repertAppli + File.separator + "images/genereVisite.png"));
    spBtnGenereVisite.setContent(imgVisiteGenere);
    Tooltip t4 = new Tooltip(rb.getString("genererVisite"));
    t4.setStyle(tooltipStyle);
    spBtnGenereVisite.setTooltip(t4);
    barreBouton.getChildren().add(spBtnGenereVisite);
    imgVisiteGenere.setDisable(true);
    imgVisiteGenere.setOpacity(0.3);
    Separator sepImages1 = new Separator(Orientation.VERTICAL);
    sepImages1.prefHeight(200);
    barreBouton.getChildren().add(sepImages1);
    /*
     Bouton equi -> faces de  Cube
     */
    ScrollPane spBtnEqui2Cube = new ScrollPane();
    spBtnEqui2Cube.getStyleClass().add("menuBarreOutils");
    spBtnEqui2Cube.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnEqui2Cube.setPrefHeight(35);
    spBtnEqui2Cube.setMaxHeight(35);
    spBtnEqui2Cube.setPadding(new Insets(2));
    spBtnEqui2Cube.setPrefWidth(109);

    HBox.setMargin(spBtnEqui2Cube, new Insets(5, 15, 0, 250));
    imgEqui2Cube = new ImageView(new Image("file:" + repertAppli + File.separator + "images/equi2cube.png"));
    spBtnEqui2Cube.setContent(imgEqui2Cube);
    Tooltip t6 = new Tooltip(rb.getString("outilsEqui2Cube"));
    t6.setStyle(tooltipStyle);
    spBtnEqui2Cube.setTooltip(t6);
    barreBouton.getChildren().add(spBtnEqui2Cube);

    /*
     Bouton faces de cube -> equi
     */
    ScrollPane spBtnCube2Equi = new ScrollPane();
    spBtnCube2Equi.getStyleClass().add("menuBarreOutils");
    spBtnCube2Equi.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnCube2Equi.setPrefHeight(35);
    spBtnCube2Equi.setMaxHeight(35);
    spBtnCube2Equi.setPadding(new Insets(2));
    spBtnCube2Equi.setPrefWidth(109);

    HBox.setMargin(spBtnCube2Equi, new Insets(5, 25, 0, 0));
    imgCube2Equi = new ImageView(new Image("file:" + repertAppli + File.separator + "images/cube2equi.png"));
    spBtnCube2Equi.setContent(imgCube2Equi);
    Tooltip t5 = new Tooltip(rb.getString("outilsCube2Equi"));
    t5.setStyle(tooltipStyle);
    spBtnCube2Equi.setTooltip(t5);
    barreBouton.getChildren().add(spBtnCube2Equi);

    myPane.getChildren().addAll(menuPrincipal, barreBouton);
    racine.getChildren().add(myPane);
    nouveauProjet.setOnAction((ActionEvent e) -> {
        projetsNouveau();
    });
    chargeProjet.setOnAction((ActionEvent e) -> {
        try {
            try {
                projetCharge();
            } catch (InterruptedException ex) {
                Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    sauveProjet.setOnAction((ActionEvent e) -> {
        try {
            projetSauve();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    sauveSousProjet.setOnAction((ActionEvent e) -> {
        try {
            projetSauveSous();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    visiteGenere.setOnAction((ActionEvent e) -> {
        try {
            genereVisite();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    fermerProjet.setOnAction((ActionEvent e) -> {
        try {
            projetsFermer();
        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    ajouterPano.setOnAction((ActionEvent e) -> {
        try {
            panoramiquesAjouter();
        } catch (InterruptedException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    ajouterPlan.setOnAction((ActionEvent e) -> {
        planAjouter();
    });
    aPropos.setOnAction((ActionEvent e) -> {
        aideapropos();
    });
    aide.setOnAction((ActionEvent e) -> {
        AideDialogController.affiche();
    });

    chargerModele.setOnAction((ActionEvent e) -> {
        try {
            modeleCharger();

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

    sauverModele.setOnAction((ActionEvent e) -> {
        try {
            modeleSauver();

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

    cube2EquiTransformation.setOnAction((ActionEvent e) -> {
        transformationCube2Equi();
    });

    equi2CubeTransformation.setOnAction((ActionEvent e) -> {
        transformationEqui2Cube();
    });
    affichageVisite.setOnAction((ActionEvent e) -> {
        tabPaneEnvironnement.getSelectionModel().select(0);
    });
    affichageInterface.setOnAction((ActionEvent e) -> {
        tabPaneEnvironnement.getSelectionModel().select(1);
    });
    affichagePlan.setOnAction((ActionEvent e) -> {
        if (!tabPlan.isDisabled()) {
            tabPaneEnvironnement.getSelectionModel().select(2);
        }
    });

    configTransformation.setOnAction((ActionEvent e) -> {
        try {
            ConfigDialogController cfg = new ConfigDialogController();
            cfg.afficheFenetre();

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

    spBtnNouvprojet.setOnMouseClicked((MouseEvent t) -> {
        projetsNouveau();
    });
    spBtnOuvrirProjet.setOnMouseClicked((MouseEvent t) -> {
        try {
            try {
                projetCharge();
            } catch (InterruptedException ex) {
                Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
            }

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnSauveProjet.setOnMouseClicked((MouseEvent t) -> {
        try {
            projetSauve();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnAjoutePano.setOnMouseClicked((MouseEvent t) -> {
        try {
            panoramiquesAjouter();
        } catch (InterruptedException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnAjoutePlan.setOnMouseClicked((MouseEvent t) -> {
        planAjouter();
    });
    spBtnGenereVisite.setOnMouseClicked((MouseEvent t) -> {
        try {
            genereVisite();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnEqui2Cube.setOnMouseClicked((MouseEvent t) -> {
        transformationEqui2Cube();
    });
    spBtnCube2Equi.setOnMouseClicked((MouseEvent t) -> {
        transformationCube2Equi();
    });

}

From source file:fr.amap.lidar.amapvox.gui.MainFrameController.java

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

    this.resourceBundle = rb;

    viewer3DPanelController.setResourceBundle(rb);

    initStrings(rb);

    colorPickerSeries.valueProperty().addListener(new ChangeListener<javafx.scene.paint.Color>() {
        @Override
        public void changed(ObservableValue<? extends javafx.scene.paint.Color> observable,
                javafx.scene.paint.Color oldValue, javafx.scene.paint.Color newValue) {
            if (listViewVoxelsFilesChart.getSelectionModel().getSelectedItems().size() == 1) {
                listViewVoxelsFilesChart.getSelectionModel().getSelectedItem().getSeriesParameters()
                        .setColor(new Color((float) newValue.getRed(), (float) newValue.getGreen(),
                                (float) newValue.getBlue(), 1.0f));
            }
        }
    });

    comboboxScript.getItems().setAll("Daniel script");

    vboxWeighting.disableProperty().bind(checkboxEnableWeighting.selectedProperty().not());

    checkboxEnableWeighting.selectedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue && textAreaWeighting.getText().isEmpty()) {

                int selectedVoxTab = tabPaneVoxelisation.getSelectionModel().getSelectedIndex();

                if (selectedVoxTab == 0) { //ALS
                    fillWeightingData(EchoesWeightParams.DEFAULT_ALS_WEIGHTING);
                } else if (selectedVoxTab == 1) { //TLS
                    fillWeightingData(EchoesWeightParams.DEFAULT_TLS_WEIGHTING);
                }
            }
        }
    });

    /*comboboxTransMode.getItems().setAll(1, 2, 3);
    comboboxTransMode.getSelectionModel().selectFirst();
            
    comboboxPathLengthMode.getItems().setAll("A", "B");
    comboboxPathLengthMode.getSelectionModel().selectFirst();*/

    helpButtonNaNsCorrection.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            helpButtonNaNsCorrectionController.showHelpDialog(resourceBundle.getString("help_NaNs_correction"));
        }
    });

    helpButtonAutoBBox.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            helpButtonAutoBBoxController.showHelpDialog(resourceBundle.getString("help_bbox"));
        }
    });

    helpButtonHemiPhoto.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            helpButtonHemiPhotoController.showHelpDialog(resourceBundle.getString("help_hemiphoto"));
        }
    });

    buttonHelpEmptyShotsFilter.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            buttonHelpEmptyShotsFilterController
                    .showHelpDialog(resourceBundle.getString("help_empty_shots_filter"));
        }
    });

    /*work around, the divider positions values are defined in the fxml,
    but when the window is initialized the values are lost*/
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            splitPaneMain.setDividerPositions(0.75f);
            splitPaneVoxelization.setDividerPositions(0.45f);
        }
    });

    initValidationSupport();
    initPostProcessTab();

    listViewTransmittanceMapSensorPositions.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    listViewTaskList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    MenuItem menuItemPadValue1m = new MenuItem("1m voxel size");
    addMenuItemPadValue(menuItemPadValue1m, 3.536958f);

    MenuItem menuItemPadValue2m = new MenuItem("2m voxel size");
    addMenuItemPadValue(menuItemPadValue2m, 2.262798f);

    MenuItem menuItemPadValue3m = new MenuItem("3m voxel size");
    addMenuItemPadValue(menuItemPadValue3m, 1.749859f);

    MenuItem menuItemPadValue4m = new MenuItem("4m voxel size");
    addMenuItemPadValue(menuItemPadValue4m, 1.3882959f);

    MenuItem menuItemPadValue5m = new MenuItem("5m voxel size");
    addMenuItemPadValue(menuItemPadValue5m, 1.0848f);

    menuButtonAdvisablePADMaxValues.getItems().addAll(menuItemPadValue1m, menuItemPadValue2m,
            menuItemPadValue3m, menuItemPadValue4m, menuItemPadValue5m);

    fileChooserSaveCanopyAnalyserOutputFile = new FileChooserContext();
    fileChooserSaveCanopyAnalyserCfgFile = new FileChooserContext();
    fileChooserSaveTransmittanceSimCfgFile = new FileChooserContext();
    fileChooserOpenCanopyAnalyserInputFile = new FileChooserContext();
    listViewCanopyAnalyzerSensorPositions.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    ContextMenu contextMenuProductsList = new ContextMenu();
    MenuItem openImageItem = new MenuItem(RS_STR_OPEN_IMAGE);
    openImageItem.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            File selectedFile = listViewProductsFiles.getSelectionModel().getSelectedItem();

            showImage(selectedFile);
        }
    });

    Menu menuEdit = new Menu(RS_STR_EDIT);

    MenuItem menuItemEditVoxels = new MenuItem("Remove voxels (delete key)");
    MenuItem menuItemFitToContent = new MenuItem("Fit to content");
    MenuItem menuItemCrop = new MenuItem("Crop");

    menuEdit.getItems().setAll(menuItemEditVoxels, menuItemFitToContent, menuItemCrop);

    menuItemFitToContent.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                fitVoxelSpaceToContent(selectedItem);
            }
        }
    });

    menuItemEditVoxels.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                editVoxelSpace(selectedItem);
            }
        }
    });

    menuItemCrop.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                try {
                    voxelSpaceCroppingFrameController.setVoxelFile(selectedItem);
                    voxelSpaceCroppingFrame.show();
                } catch (Exception ex) {
                    showErrorDialog(ex);
                }
            }
        }
    });

    Menu menuExport = new Menu(RS_STR_EXPORT);
    MenuItem menuItemExportDartMaket = new MenuItem("Dart (maket.txt)");
    MenuItem menuItemExportDartPlots = new MenuItem("Dart (plots.xml)");
    MenuItem menuItemExportMeshObj = new MenuItem("Mesh (*.obj)");

    menuItemExportDartMaket.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                exportDartMaket(selectedItem);
            }
        }
    });

    menuItemExportDartPlots.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                exportDartPlots(selectedItem);
            }
        }
    });

    menuItemExportMeshObj.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                exportMeshObj(selectedItem);
            }
        }
    });

    menuExport.getItems().setAll(menuItemExportDartMaket, menuItemExportDartPlots, menuItemExportMeshObj);

    MenuItem menuItemInfo = new MenuItem(RS_STR_INFO);

    menuItemInfo.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            Alert alert = new Alert(AlertType.INFORMATION);

            File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                VoxelFileReader reader;
                try {
                    reader = new VoxelFileReader(selectedItem);
                    VoxelSpaceInfos voxelSpaceInfos = reader.getVoxelSpaceInfos();
                    alert.setTitle("Information");
                    alert.setHeaderText("Voxel space informations");
                    alert.setContentText(voxelSpaceInfos.toString());
                    alert.show();
                } catch (Exception ex) {
                    showErrorDialog(ex);
                }

            }
        }
    });

    final MenuItem menuItemOpenContainingFolder = new MenuItem(RS_STR_OPEN_CONTAINING_FOLDER);

    menuItemOpenContainingFolder.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {

            final File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem();

            if (selectedItem != null) {
                if (Desktop.isDesktopSupported()) {
                    new Thread(() -> {
                        try {
                            Desktop.getDesktop().open(selectedItem.getParentFile());
                        } catch (IOException ex) {
                            logger.error("Cannot open directory " + selectedItem);
                        }
                    }).start();
                }

            }

        }
    });

    listViewProductsFiles.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
        @Override
        public void handle(ContextMenuEvent event) {

            if (listViewProductsFiles.getSelectionModel().getSelectedIndices().size() == 1) {

                File selectedFile = listViewProductsFiles.getSelectionModel().getSelectedItem();
                String extension = FileManager.getExtension(selectedFile);

                switch (extension) {
                case ".png":
                case ".bmp":
                case ".jpg":
                    contextMenuProductsList.getItems().setAll(openImageItem, menuItemOpenContainingFolder);
                    contextMenuProductsList.show(listViewProductsFiles, event.getScreenX(), event.getScreenY());
                    break;
                case ".vox":

                default:
                    if (VoxelFileReader.isFileAVoxelFile(selectedFile)) {
                        contextMenuProductsList.getItems().setAll(menuItemInfo, menuItemOpenContainingFolder,
                                menuEdit, menuExport);
                        contextMenuProductsList.show(listViewProductsFiles, event.getScreenX(),
                                event.getScreenY());
                    }
                }

            }

        }
    });

    ContextMenu contextMenuLidarScanEdit = new ContextMenu();
    MenuItem editItem = new MenuItem("Edit");

    editItem.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {

            filterFrameController.setFilters("Reflectance", "Deviation", "Amplitude");
            filterFrame.show();

            filterFrame.setOnHidden(new EventHandler<WindowEvent>() {

                @Override
                public void handle(WindowEvent event) {

                    if (filterFrameController.getFilter() != null) {
                        ObservableList<LidarScan> items = listViewHemiPhotoScans.getSelectionModel()
                                .getSelectedItems();
                        for (LidarScan scan : items) {
                            scan.filters.add(filterFrameController.getFilter());
                        }
                    }
                }
            });
        }
    });

    contextMenuLidarScanEdit.getItems().add(editItem);

    listViewHemiPhotoScans.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    listViewHemiPhotoScans.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {

        @Override
        public void handle(ContextMenuEvent event) {
            contextMenuLidarScanEdit.show(listViewHemiPhotoScans, event.getScreenX(), event.getScreenY());
        }
    });

    /**LAD tab initialization**/
    comboboxLADChoice.getItems().addAll(LeafAngleDistribution.Type.UNIFORM, LeafAngleDistribution.Type.SPHERIC,
            LeafAngleDistribution.Type.ERECTOPHILE, LeafAngleDistribution.Type.PLANOPHILE,
            LeafAngleDistribution.Type.EXTREMOPHILE, LeafAngleDistribution.Type.PLAGIOPHILE,
            LeafAngleDistribution.Type.HORIZONTAL, LeafAngleDistribution.Type.VERTICAL,
            LeafAngleDistribution.Type.ELLIPSOIDAL, LeafAngleDistribution.Type.ELLIPTICAL,
            LeafAngleDistribution.Type.TWO_PARAMETER_BETA);

    comboboxLADChoice.getSelectionModel().select(LeafAngleDistribution.Type.SPHERIC);
    comboboxLADChoice.getSelectionModel().selectedItemProperty()
            .addListener(new ChangeListener<LeafAngleDistribution.Type>() {

                @Override
                public void changed(ObservableValue<? extends LeafAngleDistribution.Type> observable,
                        LeafAngleDistribution.Type oldValue, LeafAngleDistribution.Type newValue) {

                    if (newValue == LeafAngleDistribution.Type.TWO_PARAMETER_BETA
                            || newValue == LeafAngleDistribution.Type.ELLIPSOIDAL) {

                        hboxTwoBetaParameters.setVisible(true);

                        if (newValue == LeafAngleDistribution.Type.ELLIPSOIDAL) {
                            labelLADBeta.setVisible(false);
                        } else {
                            labelLADBeta.setVisible(true);
                        }
                    } else {
                        hboxTwoBetaParameters.setVisible(false);
                    }
                }
            });

    ToggleGroup ladTypeGroup = new ToggleGroup();
    radiobuttonLADHomogeneous.setToggleGroup(ladTypeGroup);
    radiobuttonLADLocalEstimation.setToggleGroup(ladTypeGroup);

    /**CHART panel initialization**/

    ToggleGroup profileChartType = new ToggleGroup();
    radiobuttonPreDefinedProfile.setToggleGroup(profileChartType);
    radiobuttonFromVariableProfile.setToggleGroup(profileChartType);

    ToggleGroup profileChartRelativeHeightType = new ToggleGroup();
    radiobuttonHeightFromAboveGround.setToggleGroup(profileChartRelativeHeightType);
    radiobuttonHeightFromBelowCanopy.setToggleGroup(profileChartRelativeHeightType);

    comboboxFromVariableProfile.disableProperty().bind(radiobuttonPreDefinedProfile.selectedProperty());
    comboboxPreDefinedProfile.disableProperty().bind(radiobuttonFromVariableProfile.selectedProperty());

    hboxMaxPADVegetationProfile.visibleProperty().bind(radiobuttonPreDefinedProfile.selectedProperty());

    listViewVoxelsFilesChart.getSelectionModel().selectedIndexProperty()
            .addListener(new ChangeListener<Number>() {

                @Override
                public void changed(ObservableValue<? extends Number> observable, Number oldValue,
                        Number newValue) {

                    if (listViewVoxelsFilesChart.getSelectionModel().getSelectedItems().size() > 1) {
                        colorPickerSeries.setDisable(true);
                    } else if (listViewVoxelsFilesChart.getSelectionModel().getSelectedItems().size() == 1) {

                        VoxelFileChart selectedItem = listViewVoxelsFilesChart.getSelectionModel()
                                .getSelectedItem();
                        Color selectedItemColor = selectedItem.getSeriesParameters().getColor();

                        colorPickerSeries.setDisable(false);
                        colorPickerSeries.setValue(new javafx.scene.paint.Color(
                                selectedItemColor.getRed() / 255.0, selectedItemColor.getGreen() / 255.0,
                                selectedItemColor.getBlue() / 255.0, 1.0));

                        if (newValue.intValue() >= 0) {
                            textfieldLabelVoxelFileChart.setText(
                                    listViewVoxelsFilesChart.getItems().get(newValue.intValue()).label);
                        }
                    }
                }
            });

    textfieldLabelVoxelFileChart.textProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {

            if (listViewVoxelsFilesChart.getSelectionModel().getSelectedIndex() >= 0) {
                listViewVoxelsFilesChart.getSelectionModel().getSelectedItem().label = newValue;
            }
        }
    });

    listViewVoxelsFilesChart.getItems().addListener(new ListChangeListener<VoxelFileChart>() {

        @Override
        public void onChanged(ListChangeListener.Change<? extends VoxelFileChart> c) {

            while (c.next()) {
            }

            if (c.wasAdded() && c.getAddedSize() == c.getList().size()) {

                try {
                    VoxelFileReader reader = new VoxelFileReader(c.getList().get(0).file);
                    String[] columnNames = reader.getVoxelSpaceInfos().getColumnNames();
                    comboboxFromVariableProfile.getItems().clear();
                    comboboxFromVariableProfile.getItems().addAll(columnNames);
                    comboboxFromVariableProfile.getSelectionModel().selectFirst();
                } catch (Exception ex) {
                    logger.error("Cannot read voxel file", ex);
                }
            }

        }
    });

    anchorpaneQuadrats.disableProperty().bind(checkboxMakeQuadrats.selectedProperty().not());

    comboboxSelectAxisForQuadrats.getItems().addAll("X", "Y", "Z");
    comboboxSelectAxisForQuadrats.getSelectionModel().select(1);

    comboboxPreDefinedProfile.getItems().addAll("Vegetation (PAD)");
    comboboxPreDefinedProfile.getSelectionModel().selectFirst();

    radiobuttonSplitCountForQuadrats.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            textFieldSplitCountForQuadrats.setDisable(!newValue);
            textFieldLengthForQuadrats.setDisable(newValue);
        }
    });

    ToggleGroup chartMakeQuadratsSplitType = new ToggleGroup();
    radiobuttonLengthForQuadrats.setToggleGroup(chartMakeQuadratsSplitType);
    radiobuttonSplitCountForQuadrats.setToggleGroup(chartMakeQuadratsSplitType);

    /**Virtual measures panel initialization**/

    comboboxHemiPhotoBitmapOutputMode.getItems().addAll("Pixel", "Color");
    comboboxHemiPhotoBitmapOutputMode.getSelectionModel().selectFirst();

    ToggleGroup virtualMeasuresChoiceGroup = new ToggleGroup();

    toggleButtonLAI2000Choice.setToggleGroup(virtualMeasuresChoiceGroup);
    toggleButtonLAI2200Choice.setToggleGroup(virtualMeasuresChoiceGroup);

    comboboxChooseCanopyAnalyzerSampling.getItems().setAll(500, 4000, 10000);
    comboboxChooseCanopyAnalyzerSampling.getSelectionModel().selectFirst();

    initEchoFiltering();

    data = FXCollections.observableArrayList();

    tableViewSimulationPeriods.setItems(data);
    tableViewSimulationPeriods.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    comboboxChooseDirectionsNumber.getItems().addAll(1, 6, 16, 46, 136, 406);
    comboboxChooseDirectionsNumber.getSelectionModel().select(4);

    ToggleGroup scannerPositionsMode = new ToggleGroup();

    /*radiobuttonScannerPosSquaredArea.setToggleGroup(scannerPositionsMode);
    radiobuttonScannerPosFile.setToggleGroup(scannerPositionsMode);*/

    tableColumnPeriod.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<SimulationPeriod, String>, ObservableValue<String>>() {

                @Override
                public ObservableValue<String> call(
                        TableColumn.CellDataFeatures<SimulationPeriod, String> param) {
                    return new SimpleStringProperty(param.getValue().getPeriod().toString());
                }
            });

    tableColumnClearness.setCellValueFactory(
            new Callback<TableColumn.CellDataFeatures<SimulationPeriod, String>, ObservableValue<String>>() {

                @Override
                public ObservableValue<String> call(
                        TableColumn.CellDataFeatures<SimulationPeriod, String> param) {
                    return new SimpleStringProperty(String.valueOf(param.getValue().getClearnessCoefficient()));
                }
            });

    checkboxMultiFiles.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            anchorpaneBoundingBoxParameters.setDisable(newValue);
        }
    });

    hboxGenerateBitmapFiles.disableProperty().bind(checkboxGenerateBitmapFile.selectedProperty().not());
    hboxGenerateTextFile.disableProperty().bind(checkboxGenerateTextFile.selectedProperty().not());

    fileChooserOpenConfiguration = new FileChooser();
    fileChooserOpenConfiguration.setTitle("Choose configuration file");

    fileChooserSaveConfiguration = new FileChooserContext("cfg.xml");
    fileChooserSaveConfiguration.fc.setTitle("Choose output file");

    fileChooserOpenInputFileALS = new FileChooser();
    fileChooserOpenInputFileALS.setTitle("Open input file");
    fileChooserOpenInputFileALS.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Shot files", "*.sht"), new ExtensionFilter("Text Files", "*.txt"),
            new ExtensionFilter("Las Files", "*.las", "*.laz"));

    fileChooserOpenTrajectoryFileALS = new FileChooser();
    fileChooserOpenTrajectoryFileALS.setTitle("Open trajectory file");
    fileChooserOpenTrajectoryFileALS.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Text Files", "*.txt"));

    fileChooserOpenOutputFileALS = new FileChooser();
    fileChooserOpenOutputFileALS.setTitle("Choose output file");

    fileChooserOpenInputFileTLS = new FileChooserContext();
    fileChooserOpenInputFileTLS.fc.setTitle("Open input file");
    fileChooserOpenInputFileTLS.fc.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Text Files", "*.txt"), new ExtensionFilter("Rxp Files", "*.rxp"),
            new ExtensionFilter("Project Rsp Files", "*.rsp"));

    directoryChooserOpenOutputPathTLS = new DirectoryChooser();
    directoryChooserOpenOutputPathTLS.setTitle("Choose output path");

    directoryChooserOpenOutputPathALS = new DirectoryChooser();
    directoryChooserOpenOutputPathALS.setTitle("Choose output path");

    fileChooserSaveOutputFileTLS = new FileChooser();
    fileChooserSaveOutputFileTLS.setTitle("Save voxel file");

    fileChooserSaveTransmittanceTextFile = new FileChooser();
    fileChooserSaveTransmittanceTextFile.setTitle("Save text file");

    directoryChooserSaveTransmittanceBitmapFile = new DirectoryChooser();
    directoryChooserSaveTransmittanceBitmapFile.setTitle("Choose output directory");

    fileChooserSaveHemiPhotoOutputBitmapFile = new FileChooserContext("*.png");
    fileChooserSaveHemiPhotoOutputBitmapFile.fc.setTitle("Save bitmap file");

    directoryChooserSaveHemiPhotoOutputBitmapFile = new DirectoryChooser();
    directoryChooserSaveHemiPhotoOutputBitmapFile.setTitle("Choose bitmap files output directory");

    directoryChooserSaveHemiPhotoOutputTextFile = new DirectoryChooser();
    directoryChooserSaveHemiPhotoOutputTextFile.setTitle("Choose text files output directory");

    fileChooserSaveHemiPhotoOutputTextFile = new FileChooser();
    fileChooserSaveHemiPhotoOutputTextFile.setTitle("Save text file");

    fileChooserOpenVoxelFile = new FileChooser();
    fileChooserOpenVoxelFile.setTitle("Open voxel file");
    fileChooserOpenVoxelFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Voxel Files", "*.vox"));

    fileChooserOpenPopMatrixFile = new FileChooser();
    fileChooserOpenPopMatrixFile.setTitle("Choose matrix file");
    fileChooserOpenPopMatrixFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Text Files", "*.txt"));

    fileChooserOpenSopMatrixFile = new FileChooser();
    fileChooserOpenSopMatrixFile.setTitle("Choose matrix file");
    fileChooserOpenSopMatrixFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Text Files", "*.txt"));

    fileChooserOpenVopMatrixFile = new FileChooser();
    fileChooserOpenVopMatrixFile.setTitle("Choose matrix file");
    fileChooserOpenVopMatrixFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Text Files", "*.txt"));

    fileChooserOpenPonderationFile = new FileChooser();
    fileChooserOpenPonderationFile.setTitle("Choose ponderation file");
    fileChooserOpenPonderationFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Text Files", "*.txt"));

    fileChooserOpenDTMFile = new FileChooser();
    fileChooserOpenDTMFile.setTitle("Choose DTM file");
    fileChooserOpenDTMFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("DTM Files", "*.asc"));

    fileChooserOpenPointCloudFile = new FileChooser();
    fileChooserOpenPointCloudFile.setTitle("Choose point cloud file");
    fileChooserOpenPointCloudFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("TXT Files", "*.txt"));

    fileChooserOpenMultiResVoxelFile = new FileChooser();
    fileChooserOpenMultiResVoxelFile.setTitle("Choose voxel file");
    fileChooserOpenMultiResVoxelFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Voxel Files", "*.vox"));

    fileChooserOpenOutputFileMultiRes = new FileChooser();
    fileChooserOpenOutputFileMultiRes.setTitle("Save voxel file");

    fileChooserAddTask = new FileChooser();
    fileChooserAddTask.setTitle("Choose parameter file");
    fileChooserAddTask.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("XML Files", "*.xml"));

    fileChooserSaveDartFile = new FileChooser();
    fileChooserSaveDartFile.setTitle("Save dart file (.maket)");
    fileChooserSaveDartFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Maket File", "*.maket"));

    fileChooserOpenOutputFileMerging = new FileChooser();
    fileChooserOpenOutputFileMerging.setTitle("Choose voxel file");
    fileChooserOpenOutputFileMerging.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("Voxel Files", "*.vox"));

    fileChooserOpenScriptFile = new FileChooser();
    fileChooserOpenScriptFile.setTitle("Choose script file");

    fileChooserSaveGroundEnergyOutputFile = new FileChooser();
    fileChooserSaveGroundEnergyOutputFile.setTitle("Save ground energy file");

    fileChooserOpenPointsPositionFile = new FileChooser();
    fileChooserOpenPointsPositionFile.setTitle("Choose points file");
    fileChooserOpenPointsPositionFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"),
            new ExtensionFilter("TXT Files", "*.txt"));

    try {
        viewCapsSetupFrame = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/ViewCapsSetupFrame.fxml"));
        Parent root = loader.load();
        viewCapsSetupFrameController = loader.getController();
        viewCapsSetupFrame.setScene(new Scene(root));
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/FilteringPaneComponent.fxml"));
        anchorPaneEchoFilteringRxp = loader.load();
        filteringPaneController = loader.getController();
        filteringPaneController.setFiltersNames("Reflectance", "Amplitude", "Deviation");
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    try {
        positionImporterFrame = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/PositionImporterFrame.fxml"));
        Parent root = loader.load();
        positionImporterFrameController = loader.getController();
        positionImporterFrame.setScene(new Scene(root));
        positionImporterFrameController.setStage(positionImporterFrame);
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    try {
        voxelSpaceCroppingFrame = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/VoxelSpaceCroppingFrame.fxml"));
        Parent root = loader.load();
        voxelSpaceCroppingFrameController = loader.getController();
        voxelSpaceCroppingFrame.setScene(new Scene(root));
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    try {
        attributsImporterFrame = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/AttributsImporterFrame.fxml"));
        Parent root = loader.load();
        attributsImporterFrameController = loader.getController();
        attributsImporterFrame.setScene(new Scene(root));
        attributsImporterFrameController.setStage(attributsImporterFrame);
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    try {
        textFileParserFrameController = TextFileParserFrameController.getInstance();
    } catch (Exception ex) {
        logger.error("Cannot load fxml file", ex);
    }

    try {
        transformationFrameController = TransformationFrameController.getInstance();
        transformationFrame = transformationFrameController.getStage();
    } catch (Exception ex) {
        logger.error("Cannot load fxml file", ex);
    }

    updaterFrame = new Stage();

    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/update/UpdaterFrame.fxml"));
        Parent root = loader.load();
        updaterFrameController = loader.getController();
        updaterFrame.setScene(new Scene(root));

    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    riscanProjectExtractor = new RiscanProjectExtractor();
    ptxProjectExtractor = new PTXProjectExtractor();
    ptgProjectExtractor = new PTGProjectExtractor();

    dateChooserFrame = new Stage();

    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/DateChooserFrame.fxml"));
        Parent root = loader.load();
        dateChooserFrameController = loader.getController();
        dateChooserFrame.setScene(new Scene(root));
        dateChooserFrameController.setStage(dateChooserFrame);
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    comboboxModeALS.getItems().addAll(RS_STR_INPUT_TYPE_LAS, RS_STR_INPUT_TYPE_LAZ,
            /*RS_STR_INPUT_TYPE_XYZ, */RS_STR_INPUT_TYPE_SHOTS);

    comboboxModeALS.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {

            if (newValue.equals(RS_STR_INPUT_TYPE_SHOTS)) {
                alsVoxValidationSupport.registerValidator(textFieldTrajectoryFileALS, false,
                        Validators.unregisterValidator);
            } else {
                alsVoxValidationSupport.registerValidator(textFieldTrajectoryFileALS, false,
                        Validators.fileExistValidator);
            }
        }
    });

    comboboxModeTLS.getItems().setAll("Rxp scan", "Rsp project", "PTX",
            "PTG"/*, RS_STR_INPUT_TYPE_XYZ, RS_STR_INPUT_TYPE_SHOTS*/);
    comboboxGroundEnergyOutputFormat.getItems().setAll("txt", "png");

    comboboxLaserSpecification.getItems().addAll(LaserSpecification.getPresets());

    comboboxLaserSpecification.getSelectionModel().selectedItemProperty()
            .addListener(new ChangeListener<LaserSpecification>() {
                @Override
                public void changed(ObservableValue<? extends LaserSpecification> observable,
                        LaserSpecification oldValue, LaserSpecification newValue) {
                    DecimalFormatSymbols symb = new DecimalFormatSymbols();
                    symb.setDecimalSeparator('.');
                    DecimalFormat formatter = new DecimalFormat("#####.######", symb);

                    textFieldBeamDiameterAtExit.setText(formatter.format(newValue.getBeamDiameterAtExit()));
                    textFieldBeamDivergence.setText(formatter.format(newValue.getBeamDivergence()));
                }
            });

    comboboxLaserSpecification.getSelectionModel().select(LaserSpecification.LMS_Q560);

    comboboxLaserSpecification.disableProperty().bind(checkboxCustomLaserSpecification.selectedProperty());
    textFieldBeamDiameterAtExit.disableProperty()
            .bind(checkboxCustomLaserSpecification.selectedProperty().not());
    textFieldBeamDivergence.disableProperty().bind(checkboxCustomLaserSpecification.selectedProperty().not());

    listViewProductsFiles.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    listViewProductsFiles.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            int size = listViewProductsFiles.getSelectionModel().getSelectedIndices().size();

            if (size == 1) {
                viewer3DPanelController
                        .updateCurrentVoxelFile(listViewProductsFiles.getSelectionModel().getSelectedItem());
            }
        }
    });

    listViewTaskList.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            int size = listViewTaskList.getSelectionModel().getSelectedIndices().size();

            if (size == 1) {
                buttonLoadSelectedTask.setDisable(false);
            } else {
                buttonLoadSelectedTask.setDisable(true);
            }

            buttonExecute.setDisable(size == 0);
        }
    });

    resetMatrices();

    calculateMatrixFrame = new Stage();

    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/CalculateMatrixFrame.fxml"));
        Parent root = loader.load();
        calculateMatrixFrameController = loader.getController();
        calculateMatrixFrameController.setStage(calculateMatrixFrame);
        Scene scene = new Scene(root);
        calculateMatrixFrame.setScene(scene);
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    filterFrame = new Stage();

    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/FilterFrame.fxml"));
        Parent root = loader.load();
        filterFrameController = loader.getController();
        filterFrameController.setStage(filterFrame);
        filterFrameController.setFilters("Angle");
        filterFrame.setScene(new Scene(root));
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/export/ObjExporterDialog.fxml"));
        Parent root = loader.load();
        objExporterController = loader.getController();
        Stage s = new Stage();
        objExporterController.setStage(s);
        s.setScene(new Scene(root));
    } catch (IOException ex) {
        logger.error("Cannot load fxml file", ex);
    }

    textFieldResolution.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            voxelSpacePanelVoxelizationController.setResolution(Float.valueOf(newValue));
        }
    });

    textFieldResolution.textProperty().addListener(voxelSpacePanelVoxelizationController.getChangeListener());

    checkboxUseDTMFilter.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {

            if (checkboxUseDTMFilter.isSelected()) {
                buttonOpenDTMFile.setDisable(false);
                textfieldDTMPath.setDisable(false);
                textfieldDTMValue.setDisable(false);
                checkboxApplyVOPMatrix.setDisable(false);
                labelDTMValue.setDisable(false);
                labelDTMPath.setDisable(false);
            } else {
                buttonOpenDTMFile.setDisable(true);
                textfieldDTMPath.setDisable(true);
                textfieldDTMValue.setDisable(true);
                checkboxApplyVOPMatrix.setDisable(true);
                labelDTMValue.setDisable(true);
                labelDTMPath.setDisable(true);
            }
        }
    });

    checkboxUseVopMatrix.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            buttonSetVOPMatrix.setDisable(!newValue);
        }
    });

    checkboxUsePopMatrix.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue) {
                checkBoxUseDefaultPopMatrix.setDisable(false);
                buttonOpenPopMatrixFile.setDisable(false);
            } else {
                checkBoxUseDefaultPopMatrix.setDisable(true);
                buttonOpenPopMatrixFile.setDisable(true);
            }
        }
    });

    checkboxUseSopMatrix.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue) {
                checkBoxUseDefaultSopMatrix.setDisable(false);
                buttonOpenSopMatrixFile.setDisable(false);
            } else {
                checkBoxUseDefaultSopMatrix.setDisable(true);
                buttonOpenSopMatrixFile.setDisable(true);
            }
        }
    });

    checkboxCalculateGroundEnergy.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue) {
                anchorPaneGroundEnergyParameters.setDisable(false);
            } else {
                anchorPaneGroundEnergyParameters.setDisable(true);
            }
        }
    });

    listviewRxpScans.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<LidarScan>() {

        @Override
        public void changed(ObservableValue<? extends LidarScan> observable, LidarScan oldValue,
                LidarScan newValue) {
            if (newValue != null) {
                sopMatrix = newValue.matrix;
                updateResultMatrix();
            }
        }
    });

    comboboxModeTLS.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {

            switch (newValue.intValue()) {

            case 1:
            case 2:
            case 3:
                listviewRxpScans.setDisable(false);
                checkboxMergeAfter.setDisable(false);
                textFieldMergedFileName.setDisable(false);
                disableSopMatrixChoice(false);
                labelTLSOutputPath.setText("Output path");
                break;

            default:
                listviewRxpScans.setDisable(true);
                checkboxMergeAfter.setDisable(true);
                textFieldMergedFileName.setDisable(true);
                //disableSopMatrixChoice(true);
                labelTLSOutputPath.setText("Output file");
            }

            if (newValue.intValue() == 0 || newValue.intValue() == 1) {
                checkboxEmptyShotsFilter.setDisable(false);
            } else {
                checkboxEmptyShotsFilter.setDisable(true);
            }
        }
    });

    tabPaneVoxelisation.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {

            switch (newValue.intValue()) {

            case 1:
                disableSopMatrixChoice(false);
                disablePopMatrixChoice(false);
                checkboxEmptyShotsFilter.setDisable(false);
                break;

            default:
                disableSopMatrixChoice(true);
                disablePopMatrixChoice(true);
                checkboxEmptyShotsFilter.setDisable(true);
            }

            switch (newValue.intValue()) {
            case 0:
                checkboxCalculateGroundEnergy.setDisable(false);

                if (checkboxCalculateGroundEnergy.isSelected()) {
                    anchorPaneGroundEnergyParameters.setDisable(true);
                    checkboxCalculateGroundEnergy.setDisable(false);

                }

                anchorPaneEchoFiltering.getChildren().set(0, anchorPaneEchoFilteringClassifications);

                //anchorPaneEchoFilteringClassifications.setVisible(true);
                anchorpaneBoundingBoxParameters.setDisable(checkboxMultiFiles.isSelected());
                hboxAutomaticBBox.setDisable(false);
                break;
            default:
                anchorPaneGroundEnergyParameters.setDisable(true);
                checkboxCalculateGroundEnergy.setDisable(true);
                anchorPaneEchoFiltering.getChildren().set(0, anchorPaneEchoFilteringRxp);
                //anchorPaneEchoFilteringClassifications.setVisible(false);
                anchorpaneBoundingBoxParameters.setDisable(false);
                hboxAutomaticBBox.setDisable(true);
            }
        }
    });

    int availableCores = Runtime.getRuntime().availableProcessors();

    sliderRSPCoresToUse.setMin(1);
    sliderRSPCoresToUse.setMax(availableCores);
    sliderRSPCoresToUse.setValue(availableCores);

    textFieldInputFileALS.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textFieldTrajectoryFileALS.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textFieldOutputFileALS.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textFieldInputFileTLS.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textFieldOutputFileMerging.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textfieldDTMPath.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textFieldOutputFileGroundEnergy.setOnDragOver(DragAndDropHelper.dragOverEvent);
    listViewTaskList.setOnDragOver(DragAndDropHelper.dragOverEvent);
    listViewProductsFiles.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textfieldVoxelFilePathTransmittance.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textfieldOutputTextFilePath.setOnDragOver(DragAndDropHelper.dragOverEvent);
    textfieldOutputBitmapFilePath.setOnDragOver(DragAndDropHelper.dragOverEvent);

    textFieldInputFileALS.setOnDragDropped(new EventHandler<DragEvent>() {
        @Override
        public void handle(DragEvent event) {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles() && db.getFiles().size() == 1) {
                success = true;
                for (File file : db.getFiles()) {
                    if (file != null) {
                        textFieldInputFileALS.setText(file.getAbsolutePath());
                        selectALSInputMode(file);
                    }
                }
            }
            event.setDropCompleted(success);
            event.consume();
        }
    });
    textFieldTrajectoryFileALS.setOnDragDropped(new EventHandler<DragEvent>() {
        @Override
        public void handle(DragEvent event) {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles() && db.getFiles().size() == 1) {
                success = true;
                for (File file : db.getFiles()) {
                    if (file != null) {
                        onTrajectoryFileChoosed(file);
                    }
                }
            }
            event.setDropCompleted(success);
            event.consume();
        }
    });

    textFieldInputFileTLS.setOnDragDropped(new EventHandler<DragEvent>() {
        @Override
        public void handle(DragEvent event) {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles() && db.getFiles().size() == 1) {
                success = true;
                for (File file : db.getFiles()) {
                    if (file != null) {
                        onInputFileTLSChoosed(file);
                    }
                }
            }
            event.setDropCompleted(success);
            event.consume();
        }
    });

    setDragDroppedSingleFileEvent(textFieldOutputFileALS);
    setDragDroppedSingleFileEvent(textFieldOutputFileMerging);
    setDragDroppedSingleFileEvent(textfieldDTMPath);
    setDragDroppedSingleFileEvent(textFieldOutputFileGroundEnergy);
    setDragDroppedSingleFileEvent(textfieldVoxelFilePathTransmittance);
    setDragDroppedSingleFileEvent(textfieldOutputTextFilePath);
    setDragDroppedSingleFileEvent(textfieldOutputBitmapFilePath);

    listViewTaskList.setOnDragDropped(new EventHandler<DragEvent>() {
        @Override
        public void handle(DragEvent event) {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
                success = true;
                for (File file : db.getFiles()) {
                    addFileToTaskList(file);
                }
            }
            event.setDropCompleted(success);
            event.consume();
        }
    });

    listViewProductsFiles.setOnDragDropped(new EventHandler<DragEvent>() {
        @Override
        public void handle(DragEvent event) {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
                success = true;
                for (File file : db.getFiles()) {
                    addFileToProductsList(file);
                }
            }
            event.setDropCompleted(success);
            event.consume();
        }
    });

    listViewProductsFiles.setOnDragDetected(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {

            Dragboard db = listViewProductsFiles.startDragAndDrop(TransferMode.COPY);

            ClipboardContent content = new ClipboardContent();
            content.putFiles(listViewProductsFiles.getSelectionModel().getSelectedItems());
            db.setContent(content);

            event.consume();
        }
    });

    addPointcloudFilterComponent();

    checkboxUsePointcloudFilter.selectedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {

            hBoxPointCloudFiltering.setDisable(!newValue);

            ObservableList<Node> list = vBoxPointCloudFiltering.getChildren();
            for (Node n : list) {
                if (n instanceof PointCloudFilterPaneComponent) {

                    PointCloudFilterPaneComponent panel = (PointCloudFilterPaneComponent) n;
                    panel.disableContent(!newValue);
                }
            }

            buttonAddPointcloudFilter.setDisable(!newValue);

        }
    });

    //displayGThetaAllDistributions();
}

From source file:patientmanagerv1.HomeController.java

@Override
public void initialize(URL url, ResourceBundle rb) {

    //start with the forum and the common questions page, add-on the profile page and private messaging features

    //passLoaded = false;

    //sets the current Patient
    try {//from   ww  w .j  a  v a2 s. c  o m
        String entireFileText = new Scanner(new File(installationPath + "/currentpatient.txt"))
                .useDelimiter("//A").next();
        String[] nameArray = entireFileText.split(",");

        firstName = nameArray[0].toLowerCase();
        lastName = nameArray[1].toLowerCase();
        dob = nameArray[2];
    } catch (Exception e) {
    }

    //checks the signed status
    try {
        FileReader reader = new FileReader(
                installationPath + "/userdata/" + firstName + lastName + dob + "/EvaluationForm/signed.txt");
        //+ "/userdata/" + get.currentPatientFirstName + get.currentPatientLastName + "/EvaluationForm/first.txt");
        BufferedReader br = new BufferedReader(reader);
        String signedStatus = br.readLine();
        br.close();
        reader.close();

        if (signedStatus.equalsIgnoreCase("true")) {
            dccSigned = true;
        } else {
            dccSigned = false;
        }

        FileReader reader2 = new FileReader(installationPath + "/userdata/" + firstName + lastName + dob
                + "/EvaluationForm/assistantsigned.txt");
        //+ "/userdata/" + get.currentPatientFirstName + get.currentPatientLastName + "/EvaluationForm/first.txt");
        BufferedReader br2 = new BufferedReader(reader2);
        String assistantSigned = br2.readLine();
        br2.close();
        reader2.close();

        if (assistantSigned.equalsIgnoreCase("true")) {
            partnerSigned = true;
        } else {
            partnerSigned = false;
        }

        /*saveButton.setDisable(false);
        sign.setVisible(true);
        sign.setDisable(true);
        signature.setVisible(false);*/

        if (signedStatus.equalsIgnoreCase("false") && (assistantSigned.equalsIgnoreCase("false"))) {
            saveButton.setDisable(false);
            sign.setVisible(true);
            sign.setDisable(false);
            assistantsign.setVisible(true);
            assistantsign.setDisable(false);
            assistantsignature.setVisible(false);
            signature.setVisible(false);
            signature2.setVisible(false);
            ap.setDisable(false);
        } else if (signedStatus.equalsIgnoreCase("true") && (assistantSigned.equalsIgnoreCase("false"))) {
            saveButton.setDisable(true);
            sign.setVisible(false);
            assistantsign.setVisible(true);
            assistantsign.setDisable(false);
            assistantsignature.setVisible(false);
            signature.setVisible(true);
            signature2.setVisible(true);
            signature.setText("This document has been digitally signed by David Zhvikov MD");
            ap.setDisable(true);
        } else if (signedStatus.equalsIgnoreCase("false") && (assistantSigned.equalsIgnoreCase("true"))) {
            saveButton.setDisable(true);
            sign.setVisible(true);
            assistantsign.setVisible(false);
            assistantsign.setDisable(true);
            assistantsignature.setVisible(true);
            signature.setVisible(false);
            signature2.setVisible(false);
            signature.setText("This document has been digitally signed by David Zhvikov MD");
            ap.setDisable(true);
        } else {
            saveButton.setDisable(true);
            sign.setVisible(false);
            assistantsign.setVisible(false);
            assistantsign.setDisable(true);
            assistantsignature.setVisible(true);
            signature.setVisible(true);
            signature2.setVisible(true);
            signature.setText("This document has been digitally signed by David Zhvikov MD");
            ap.setDisable(true);
        }
    } catch (Exception e) {
    }

    //loads the ListView

    try {
        FileReader r2 = new FileReader(
                installationPath + "/userdata/" + firstName + lastName + dob + "/ProgressReports.txt");
        BufferedReader b2 = new BufferedReader(r2);

        String s;
        ArrayList progressNotes = new ArrayList();

        while ((s = b2.readLine()) != null) {
            //System.out.println(s);
            progressNotes.add(s);
        }

        b2.close();
        r2.close();

        //Adds the Progress Notes to the ListView

        ObservableList<String> items = FXCollections.observableArrayList("Single", "Double");
        items.clear();

        for (int counter = 0; counter < progressNotes.size(); counter++) {
            items.add(progressNotes.get(counter).toString());
        }

        listOfProgressReports.setItems(items);

        //String[] ethnicityArray = ethnicity.split(",");
    } catch (Exception e) {
        //System.out.println("file not found");
    }

    //initializes the evaluation form [with the new patient's name] for the current patient
    fillName();

    fillDOB();

    fillAge(loaded);

    fillGender();

    fillMaritalStatus();

    fillEthnicity();

    fillReferredBy();

    fillReasonForReferral();

    fillSourceOfInformation();

    fillReliabilityOfInformation();

    fillHistoryOfPresentIllness();

    fillSignsSymptoms();

    fillCurrentMedications();

    fillPastPsychiatricHistory();

    fillPastHistoryOf();

    fillHistoryOfMedicationTrialsInThePast();

    fillSubstanceUseHistory();

    fillDeniesHistoryOf();

    fillSocialHistory();

    fillParentsSiblingsChildren();

    fillFamilyHistoryOfMentalIllness();

    fillEducation();

    fillEmployment();

    fillLegalHistory();

    fillPastMedicalHistory();

    fillAllergies();

    fillAppearance();

    fillEyeContact();

    fillAttitude();

    fillMotorActivity();

    fillAffect();

    fillMood();

    fillSpeech();

    fillThoughtProcess();

    fillThoughtContent();

    fillPerception();

    fillSuicidality();

    fillHomicidality();

    fillOrientation();

    fillShortTermMemory();

    fillLongTermMemory();

    fillGeneralFundOfKnowledge();

    fillIntellect();

    fillAbstraction();

    fillJudgementAndInsight();

    fillClinicalNotes();

    fillTreatmentPlan();

    fillSideEffects();

    fillLabs();

    fillEnd();

    fillSignatureZone();

    //        currentPatientFirstName = get.currentPatientFirstName;
    //        currentPatientLastName = get.currentPatientLastName;

    //sets the current patient
    /*try
    {
    String entireFileText = new Scanner(new File(installationPath + "/Patients.txt")).useDelimiter("//A").next();
    String[] arrayOfNames = entireFileText.split(";");
            
            
    System.out.println("Patient Name: " + arrayOfNames[arrayOfNames.length - 1]);
            
    String nameWithComma = arrayOfNames[arrayOfNames.length - 1];
    String[] nameArray = nameWithComma.split(",");
            
    firstName = nameArray[0].toLowerCase();
    lastName = nameArray[1].toLowerCase();
            
            
            
    }
    catch(Exception e)
    {}*/

    /*ArrayList progressNotes = new ArrayList();
            
    for(int i = 0; i < listOfProgressReports.getItems().size(); i++)
    {
        progressNotes.add(listOfProgressReports.getItems().get(i));
    }*/

    //broken and betrayed
    //of the ecsts's you've shown me.
    //...for me, italicsmaster, she put emphasis/lingered on the word. "M"

    menu.getMenus().removeAll();
    Menu file = new Menu("File");
    Menu edit = new Menu("Edit");
    Menu view = new Menu("View");
    Menu help = new Menu("About");
    Menu speech = new Menu("Speech Options");

    MenuItem save = new MenuItem("Save");
    MenuItem print = new MenuItem("Print");
    MenuItem printWithSettings = new MenuItem("Print With Settings");
    MenuItem export = new MenuItem("Export to");
    MenuItem logout = new MenuItem("Return to Patient Selection");
    MenuItem deleteThisPatient = new MenuItem("Delete This Patient");
    MenuItem exit = new MenuItem("Exit");

    MenuItem undo = new MenuItem("Undo (ctrl+z)");
    MenuItem redo = new MenuItem("Redo (ctrl+y)");
    MenuItem selectAll = new MenuItem("Select All (ctrl+A)");
    MenuItem cut = new MenuItem("Cut (ctrl+x)");
    MenuItem copy = new MenuItem("Copy (ctrl+c)");
    MenuItem paste = new MenuItem("Paste (ctrl+v)");
    MenuItem enableBackdoorModifications = new MenuItem("Enable Modification of this Evaluation Post-Signing");

    Menu submenu1 = new Menu("Create");
    Menu submenu2 = new Menu("Load");
    Menu submenu3 = new Menu("New");
    MenuItem createProgressReport = new MenuItem("Progress Report");
    MenuItem loadProgressReport = new MenuItem("Progress Report");
    MenuItem deleteProgressReport = new MenuItem("Delete selected progress report");
    submenu1.getItems().add(submenu3);
    submenu3.getItems().add(createProgressReport);
    submenu2.getItems().add(loadProgressReport);

    MenuItem howToUse = new MenuItem("How to use patient manager");
    MenuItem versionInfo = new MenuItem("About Patient Manager/Version Info");

    /*MenuItem read = new MenuItem("Read to me");
    MenuItem launch = new MenuItem("Launch Dictation");*/
    //read to me menu, dictation menu- select a document to read aloud, read this passage aloud, launch windows in-built dictation, download brainac dictation online
    Menu read = new Menu("Read to me");
    Menu launch = new Menu("Dictation");

    Menu readPassageOrFormStartStop = new Menu("Read this passage/read this form");

    MenuItem startReading1 = new MenuItem("Start");
    MenuItem stopReading1 = new MenuItem("Stop");
    MenuItem startReading2 = new MenuItem("Start");
    MenuItem stopReading2 = new MenuItem("Stop");
    Menu readUploadedDocument = new Menu("Select a document to read");
    MenuItem launchWindowsDictation = new MenuItem("Launch Windows' Built-In Dictation");
    MenuItem launchBrainacDictation = new MenuItem("Download Brainac Dictation");

    startReading1.setDisable(true);
    stopReading1.setDisable(true);
    startReading2.setDisable(true);
    stopReading2.setDisable(true);

    readPassageOrFormStartStop.getItems().add(startReading1);
    readPassageOrFormStartStop.getItems().add(stopReading1);
    readUploadedDocument.getItems().add(startReading2);
    readUploadedDocument.getItems().add(stopReading2);

    readPassageOrFormStartStop.setDisable(true);
    readUploadedDocument.setDisable(true);

    launchBrainacDictation.setDisable(true);

    read.getItems().add(readPassageOrFormStartStop);
    read.getItems().add(readUploadedDocument);
    launch.getItems().add(launchWindowsDictation);
    launch.getItems().add(launchBrainacDictation);

    file.getItems().add(save);
    file.getItems().add(print);
    file.getItems().add(printWithSettings);
    file.getItems().add(export);
    file.getItems().add(logout);
    file.getItems().add(deleteThisPatient);
    file.getItems().add(exit);

    edit.getItems().add(undo);
    edit.getItems().add(redo);
    edit.getItems().add(selectAll);
    edit.getItems().add(cut);
    edit.getItems().add(copy);
    edit.getItems().add(paste);
    edit.getItems().add(enableBackdoorModifications);

    view.getItems().add(submenu1);
    view.getItems().add(submenu2);
    view.getItems().add(deleteProgressReport);

    help.getItems().add(howToUse);
    help.getItems().add(versionInfo);

    speech.getItems().add(read);
    speech.getItems().add(launch);

    menu.prefWidthProperty().bind(masterPane.widthProperty());
    //menu.setStyle("-fx-padding: 0 20 0 20;");

    //menu.getMenus().addAll(file, edit, view, help, speech);
    menu.getMenus().add(file);
    menu.getMenus().add(edit);
    menu.getMenus().add(view);
    menu.getMenus().add(speech);
    menu.getMenus().add(help);

    undo.setDisable(true);
    redo.setDisable(true);
    cut.setDisable(true);
    copy.setDisable(true);
    paste.setDisable(true);
    selectAll.setDisable(true);

    deleteThisPatient.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {

            int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this patient?",
                    "Warning", JOptionPane.OK_CANCEL_OPTION);

            if (result == 2) {

            }

            if (result == 0) {
                int result2 = JOptionPane.showConfirmDialog(null,
                        "Are you ABSOLUTELY sure you want to delete this patient?", "Warning",
                        JOptionPane.OK_CANCEL_OPTION);

                if (result2 == 2) {

                }
                if (result2 == 0) {
                    String patientToDelete = firstName + "," + lastName + "," + dob; //listOfProgressReports.getSelectionModel().getSelectedItem().toString();

                    //            String currRepNoColons = currRep.replace(":", "");
                    //        currRepNoColons = currRepNoColons.trim();

                    //1) removes the report from the list in the file
                    try {
                        FileReader r2 = new FileReader(installationPath + "/patients.txt");
                        BufferedReader b2 = new BufferedReader(r2);

                        String s = b2.readLine();
                        String[] patients = s.split(";"); //String[] ssArray = ss.split(",");

                        /*for(int i = 0; i < patients.size(); i++)
                        {
                                
                        }*/

                        /*while((s = b2.readLine()) != null)
                        {
                            //System.out.println(s);
                                
                            if(!s.equalsIgnoreCase(patientToDelete))
                            {patients.add(s);}
                        }*/

                        b2.close();
                        r2.close();

                        File fff = new File(installationPath + "/patients.txt");
                        FileWriter ddd = new FileWriter(fff, false);
                        BufferedWriter bw = new BufferedWriter(ddd);
                        ddd.append("");
                        bw.close();
                        ddd.close();

                        for (int i = 0; i < patients.length; i++) {
                            File openProgressReportsList = new File(installationPath + "/patients.txt");
                            FileWriter fw = new FileWriter(openProgressReportsList, true);
                            BufferedWriter bufferedwriter = new BufferedWriter(fw);
                            if (!(patients[i].equalsIgnoreCase(patientToDelete))) {
                                fw.append(patients[i].toLowerCase() + ";");
                            }
                            bufferedwriter.close();
                            fw.close();
                        }
                    } catch (Exception ex) {

                    }

                    /*try{
                            FileReader reader = new FileReader(installationPath + "/userdata/" + firstName + lastName + dob + "/ProgressReports.txt");
                            BufferedReader br = new BufferedReader(reader); 
                            String fileContents = br.readLine();
                            br.close();
                            reader.close();
                            
                            fileContents = fileContents.replace(currRep, "");
                            //System.out.println("fc:" + fileContents);
                            
                            //writes the new contents to the file:
                            //writes the new report to the list
                            File openProgressReportsList = new File(installationPath + "/userdata/" + firstName + lastName + dob + "/ProgressReports.txt");
                            FileWriter fw = new FileWriter(openProgressReportsList, false);           
                            BufferedWriter bufferedwriter = new BufferedWriter(fw);
                            fw.append(fileContents);
                            bufferedwriter.close();
                            fw.close();
                    }
                    catch(Exception e)
                    {
                            
                    }*/

                    //2) Deletes the folder for that progress report
                    try {
                        File directory = new File(installationPath + "/userdata/" + firstName + lastName + dob
                                + "/ProgressNotes");
                        File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
                        for (File dir : subdirs) {
                            File deleteThis = new File(installationPath + "/userdata/" + firstName + lastName
                                    + dob + "/ProgressNotes/" + dir.getName());
                            //System.out.println("Directory: " + dir.getName());
                            File[] filez = deleteThis.listFiles();

                            for (int i = 0; i < filez.length; i++) {
                                filez[i].delete();
                            }
                            //the wedding nightmare: red, red, dark purple-brown; big-ol red wrap/red jacket
                            deleteThis.delete();
                        }
                        File path3 = new File(installationPath + "/userdata/" + firstName + lastName + dob
                                + "/ProgressNotes");
                        File[] files3 = path3.listFiles();

                        for (int i = 0; i < files3.length; i++) {
                            files3[i].delete();
                        }
                        //the wedding nightmare: red, red, dark purple-brown; big-ol red wrap/red jacket
                        path3.delete();

                        File path2 = new File(installationPath + "/userdata/" + firstName + lastName + dob
                                + "/EvaluationForm");
                        File[] files2 = path2.listFiles();

                        for (int i = 0; i < files2.length; i++) {
                            files2[i].delete();
                        }
                        //the wedding nightmare: red, red, dark purple-brown; big-ol red wrap/red jacket
                        path2.delete();

                        File path = new File(installationPath + "/userdata/" + firstName + lastName + dob);
                        File[] files = path.listFiles();

                        for (int i = 0; i < files.length; i++) {
                            files[i].delete();
                        }
                        //the wedding nightmare: red, red, dark purple-brown; big-ol red wrap/red jacket
                        path.delete();
                        //deleteDirectory(installationPath + "/userdata/" + firstName + lastName + dob + "/ProgressNotes/" + currRepNoColons);
                        //Files.delete(installationPath + "/userdata/" + firstName + lastName + dob + "/ProgressNotes/" + currRepNoColons);

                        //PUT A MESSAGE SAYING "DELETED" HERE
                        JOptionPane.showMessageDialog(null, "Deleted!");

                        toPatientSelectionNoDialog.fire();
                    } catch (Exception exception) {
                    }
                }

            }

        }
    });

    save.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            save();
        }
    });

    versionInfo.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            JOptionPane.showMessageDialog(null, "Patient Manager Version 5.0.6 \n Compatible with: Windows 7");
        }
    });

    howToUse.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "Help: \n\n\n Print- sends the document to the default printer. Requires no passwords. \n\n Print with Settings- opens the evaluation or progress report in word so that the document can be printed using word's built-in dialog. Because the word document will be open to modification, 'print with settings' requires the physician's password. \n\n Export to- save an evaluation or progress note to the location of your choice, rather than to the default location. Requires the physician/admin's password. \n\n Enable Backdoor Modifications- allows the physician or physician's assistant(s) to reopen the forms for modification post-signing. If the physician's password is used, only his signature will become undone. If the physician's assistant(s)' password is used, both the physician's signature (if relevant) and the assitant's signature will become undone (since the physician will need to review the new modifications before re-signing his approval). \n\n Create/Load/Delete a progress note- the create & load functions are accessible directly from the interface. Deletion can only be accessed from the drop-down menu. Select a progress report prior to clicking 'load' or 'delete' \n\n Speech Options- most speech options are still a WIP, HOWEVER, you can click 'launch windows 7 native dictation' from either the interface OR the menu bar, in order to quickly access Windows' built-in dictation capabilities. \n\n Version info can be found in 'About' in the 'Help' drop-down menu on the main menu bar.");
        }
    });

    launchWindowsDictation.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            launchSpeechRecognition();
        }
    });

    exit.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(null,
                    "Do you want to save any unsaved changes before exiting?", "Save changes?",
                    JOptionPane.YES_NO_CANCEL_OPTION);

            if (result == 0) {
                saveEval();

                //some idiocy goes here
                /*try
                {
                    Audio audio = Audio.getInstance();
                    InputStream sound = audio.getAudio("Have a nice day!", Language.ENGLISH);
                    audio.play(sound);
                }
                catch(Exception excep)
                {System.out.println(excep);}*/

                System.exit(0);
            }
            if (result == 1) {
                //some idiocy goes here
                /*try
                {
                    Audio audio = Audio.getInstance();
                    InputStream sound = audio.getAudio("Have a nice day!", Language.ENGLISH);
                    audio.play(sound);
                }
                catch(Exception excep)
                {System.out.println(excep);}*/

                System.exit(0);
            }
            if (result == 2) {

            }

        }
    });

    enableBackdoorModifications.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            enableBackdoorModifications();
        }
    });

    deleteProgressReport.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            deleteProgressReport();
        }
    });

    //<MenuItem fx:id="loadProgressReport" onAction="#loadProgressReport" />

    loadProgressReport.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            load.fire();
        }
    });

    createProgressReport.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            createPN.fire();
        }
    }); //read to me menu, dictation menu- select a document to read aloud, read this passage aloud, launch windows in-built dictation, download brainac dictation online

    export.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            final Stage dialog = new Stage();
            dialog.initModality(Modality.APPLICATION_MODAL);

            final TextField textField = new TextField();
            Button submit = new Button();
            Button cancel = new Button();
            final Label label = new Label();

            cancel.setText("Cancel");
            cancel.setAlignment(Pos.CENTER);
            submit.setText("Submit");
            submit.setAlignment(Pos.BOTTOM_RIGHT);

            final VBox dialogVbox = new VBox(20);
            dialogVbox.getChildren().add(new Text("Enter the master password: "));
            dialogVbox.getChildren().add(textField);
            dialogVbox.getChildren().add(submit);
            dialogVbox.getChildren().add(cancel);
            dialogVbox.getChildren().add(label);

            Scene dialogScene = new Scene(dialogVbox, 300, 200);
            dialog.setScene(dialogScene);
            dialog.setTitle("Security/Physician Authentication");
            dialog.show();

            submit.setOnAction(new EventHandler<ActionEvent>() {

                public void handle(ActionEvent anEvent) {
                    String password = textField.getText();

                    if (password.equalsIgnoreCase("protooncogene")) {
                        dialog.close();

                        export();

                    } else {
                        label.setText("The password you entered is incorrect. Please try again.");
                    }

                }
            });

            cancel.setOnAction(new EventHandler<ActionEvent>() {

                public void handle(ActionEvent anEvent) {
                    dialog.close();
                    //close the window here
                }
            });

        }
    });

    print.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            print();
        }
    });
    printWithSettings.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            printAdv();
        }
    });
    logout.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent e) {
            toPatientSelection.fire();
        }
    });

    ///"sometime during s-y lol."

}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @param vbRacine panel d'installation du menu
 * @throws Exception Exceptions/*w w w. java  2s. co m*/
 */
private static void creeMenu(VBox vbRacine) throws Exception {
    VBox vbMonPanneau = new VBox();

    vbMonPanneau.setPrefHeight(80);
    vbMonPanneau.setPrefWidth(3000);
    mbarPrincipal.setMinHeight(29);
    mbarPrincipal.setPrefHeight(29);
    mbarPrincipal.setMaxHeight(29);
    mbarPrincipal.setPrefWidth(3000);
    if (isMac()) {
        mbarPrincipal.setUseSystemMenuBar(true);
    }
    /* 
     Menu projets
     */
    Menu mnuProjet = new Menu(rbLocalisation.getString("projets"));

    mbarPrincipal.getMenus().add(mnuProjet);
    mniNouveauProjet = new MenuItem(rbLocalisation.getString("nouveauProjet"));
    mniNouveauProjet.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.SHORTCUT_DOWN));
    mnuProjet.getItems().add(mniNouveauProjet);
    mniChargeProjet = new MenuItem(rbLocalisation.getString("ouvrirProjet"));
    mniChargeProjet.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN));

    mnuProjet.getItems().add(mniChargeProjet);
    mniSauveProjet = new MenuItem(rbLocalisation.getString("sauverProjet"));
    mniSauveProjet.setDisable(true);
    mniSauveProjet.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN));
    mnuProjet.getItems().add(mniSauveProjet);
    mniSauveSousProjet = new MenuItem(rbLocalisation.getString("sauverProjetSous"));
    mniSauveSousProjet.setDisable(true);
    mniSauveSousProjet.setAccelerator(
            new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN, KeyCodeCombination.SHIFT_DOWN));
    mnuProjet.getItems().add(mniSauveSousProjet);
    mnuDerniersProjets = new Menu(rbLocalisation.getString("derniersProjets"));
    mnuProjet.getItems().add(mnuDerniersProjets);
    fileHistoFichiers = new File(fileRepertConfig.getAbsolutePath() + File.separator + "derniersprojets.cfg");
    nombreHistoFichiers = 0;
    if (fileHistoFichiers.exists()) {
        try (BufferedReader brHistoFichiers = new BufferedReader(
                new InputStreamReader(new FileInputStream(fileHistoFichiers), "UTF-8"))) {
            while ((strTexteHisto = brHistoFichiers.readLine()) != null) {
                MenuItem menuDerniersFichiers = new MenuItem(strTexteHisto);
                mnuDerniersProjets.getItems().add(menuDerniersFichiers);
                strHistoFichiers[nombreHistoFichiers] = strTexteHisto;
                nombreHistoFichiers++;
                menuDerniersFichiers.setOnAction((e) -> {
                    MenuItem mniSousMenu = (MenuItem) e.getSource();
                    try {
                        try {
                            projetChargeNom(mniSousMenu.getText());

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

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

            }
        }
    }

    SeparatorMenuItem sepMenu1 = new SeparatorMenuItem();
    mnuProjet.getItems().add(sepMenu1);
    mniFermerProjet = new MenuItem(rbLocalisation.getString("quitterApplication"));
    mniFermerProjet.setAccelerator(new KeyCodeCombination(KeyCode.A, KeyCombination.SHORTCUT_DOWN));
    mnuProjet.getItems().add(mniFermerProjet);
    /*
     Menu affichage
     */
    Menu mnuAffichage = new Menu(rbLocalisation.getString("affichage"));
    mbarPrincipal.getMenus().add(mnuAffichage);
    mniAffichageVisite = new MenuItem(rbLocalisation.getString("main.creationVisite"));
    mniAffichageVisite.setAccelerator(new KeyCodeCombination(KeyCode.DIGIT1, KeyCombination.SHORTCUT_DOWN));
    mnuAffichage.getItems().add(mniAffichageVisite);
    mniAffichageInterface = new MenuItem(rbLocalisation.getString("main.creationInterface"));
    mniAffichageInterface.setAccelerator(new KeyCodeCombination(KeyCode.DIGIT2, KeyCombination.SHORTCUT_DOWN));
    mnuAffichage.getItems().add(mniAffichageInterface);
    setMniAffichagePlan(new MenuItem(rbLocalisation.getString("main.tabPlan")));
    getMniAffichagePlan().setAccelerator(new KeyCodeCombination(KeyCode.DIGIT3, KeyCombination.SHORTCUT_DOWN));
    getMniAffichagePlan().setDisable(true);
    mnuAffichage.getItems().add(getMniAffichagePlan());
    mniOutilsLoupe = new MenuItem(rbLocalisation.getString("main.loupe"));
    mniOutilsLoupe.setAccelerator(new KeyCodeCombination(KeyCode.L, KeyCombination.SHORTCUT_DOWN));
    mnuAffichage.getItems().add(mniOutilsLoupe);

    SeparatorMenuItem sep3 = new SeparatorMenuItem();
    mnuAffichage.getItems().add(sep3);
    mniConfigTransformation = new MenuItem(rbLocalisation.getString("affichageConfiguration"));
    mnuAffichage.getItems().add(mniConfigTransformation);

    /*
     Menu panoramiques
     */
    mnuPanoramique = new Menu(rbLocalisation.getString("panoramiques"));
    mnuPanoramique.setDisable(true);
    mbarPrincipal.getMenus().add(mnuPanoramique);
    mniAjouterPano = new MenuItem(rbLocalisation.getString("ajouterPanoramiques"));
    mniAjouterPano.setAccelerator(new KeyCodeCombination(KeyCode.A, KeyCombination.SHORTCUT_DOWN));
    mnuPanoramique.getItems().add(mniAjouterPano);
    setMniAjouterPlan(new MenuItem(rbLocalisation.getString("ajouterPlan")));
    getMniAjouterPlan().setAccelerator(new KeyCodeCombination(KeyCode.P, KeyCombination.SHORTCUT_DOWN));
    mnuPanoramique.getItems().add(getMniAjouterPlan());
    getMniAjouterPlan().setDisable(true);
    SeparatorMenuItem sep2 = new SeparatorMenuItem();
    mnuPanoramique.getItems().add(sep2);
    mniVisiteGenere = new MenuItem(rbLocalisation.getString("genererVisite"));
    mniVisiteGenere.setDisable(true);
    mniVisiteGenere.setAccelerator(new KeyCodeCombination(KeyCode.V, KeyCombination.SHORTCUT_DOWN));
    mnuPanoramique.getItems().add(mniVisiteGenere);
    /*
     Menu Modles 
     */
    mnuModeles = new Menu(rbLocalisation.getString("menuModele"));
    mbarPrincipal.getMenus().add(mnuModeles);

    mniChargerModele = new MenuItem(rbLocalisation.getString("modeleCharger"));
    mnuModeles.getItems().add(mniChargerModele);

    mniSauverModele = new MenuItem(rbLocalisation.getString("modeleSauver"));
    mnuModeles.getItems().add(mniSauverModele);

    /*
     Menu transformations 
     */
    mnuTransformation = new Menu(rbLocalisation.getString("outils"));
    mbarPrincipal.getMenus().add(mnuTransformation);
    mniEqui2CubeTransformation = new MenuItem(rbLocalisation.getString("outilsEqui2Cube"));
    mnuTransformation.getItems().add(mniEqui2CubeTransformation);
    mniCube2EquiTransformation = new MenuItem(rbLocalisation.getString("outilsCube2Equi"));
    mnuTransformation.getItems().add(mniCube2EquiTransformation);
    SeparatorMenuItem sep6 = new SeparatorMenuItem();
    mnuTransformation.getItems().add(sep6);
    mniOutilsBarre = new MenuItem(rbLocalisation.getString("outilsBarre"));
    mniOutilsBarre.setAccelerator(new KeyCodeCombination(KeyCode.B, KeyCombination.SHORTCUT_DOWN));
    mnuTransformation.getItems().add(mniOutilsBarre);
    mniOutilsDiaporama = new MenuItem(rbLocalisation.getString("outilsDiaporama"));
    mniOutilsDiaporama.setAccelerator(new KeyCodeCombination(KeyCode.D, KeyCombination.SHORTCUT_DOWN));
    mnuTransformation.getItems().add(mniOutilsDiaporama);

    /*
     Menu Aide
     */
    Menu mnuAide = new Menu(rbLocalisation.getString("aide"));
    mbarPrincipal.getMenus().add(mnuAide);
    mniAide = new MenuItem(rbLocalisation.getString("aideAide"));
    mniAide.setAccelerator(new KeyCodeCombination(KeyCode.H, KeyCombination.SHORTCUT_DOWN));
    mnuAide.getItems().add(mniAide);
    SeparatorMenuItem sep4 = new SeparatorMenuItem();
    mnuAide.getItems().add(sep4);
    mniAPropos = new MenuItem(rbLocalisation.getString("aideAPropos"));
    mnuAide.getItems().add(mniAPropos);
    //
    //        }
    //
    /*
     barre de boutons 
     */
    hbBarreBouton = new HBox();
    hbBarreBouton.getStyleClass().add("menuBarreOutils1");

    hbBarreBouton.setPrefHeight(50);
    hbBarreBouton.setMinHeight(50);
    hbBarreBouton.setPrefWidth(3000);
    /*
     Bouton nouveau Projet
     */
    ScrollPane spBtnNouvprojet = new ScrollPane();
    spBtnNouvprojet.getStyleClass().add("menuBarreOutils");
    spBtnNouvprojet.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnNouvprojet.setPrefHeight(35);
    spBtnNouvprojet.setMaxHeight(35);
    spBtnNouvprojet.setPadding(new Insets(2));
    spBtnNouvprojet.setPrefWidth(35);

    HBox.setMargin(spBtnNouvprojet, new Insets(5, 15, 0, 15));
    ivNouveauProjet = new ImageView(
            new Image("file:" + getStrRepertAppli() + File.separator + "images/nouveauProjet.png"));
    spBtnNouvprojet.setContent(ivNouveauProjet);
    Tooltip tltpNouveauProjet = new Tooltip(rbLocalisation.getString("nouveauProjet"));
    tltpNouveauProjet.setStyle(getStrTooltipStyle());
    spBtnNouvprojet.setTooltip(tltpNouveauProjet);
    hbBarreBouton.getChildren().add(spBtnNouvprojet);
    /*
     Bouton ouvrir Projet
     */
    ScrollPane spBtnOuvrirProjet = new ScrollPane();
    spBtnOuvrirProjet.getStyleClass().add("menuBarreOutils");
    spBtnOuvrirProjet.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnOuvrirProjet.setPrefHeight(35);
    spBtnOuvrirProjet.setMaxHeight(35);
    spBtnOuvrirProjet.setPadding(new Insets(2));
    spBtnOuvrirProjet.setPrefWidth(35);

    HBox.setMargin(spBtnOuvrirProjet, new Insets(5, 15, 0, 0));
    ivChargeProjet = new ImageView(
            new Image("file:" + getStrRepertAppli() + File.separator + "images/ouvrirProjet.png"));
    spBtnOuvrirProjet.setContent(ivChargeProjet);
    Tooltip tltpOuvrirProjet = new Tooltip(rbLocalisation.getString("ouvrirProjet"));
    tltpOuvrirProjet.setStyle(getStrTooltipStyle());
    spBtnOuvrirProjet.setTooltip(tltpOuvrirProjet);
    hbBarreBouton.getChildren().add(spBtnOuvrirProjet);

    /*
     Bouton sauve Projet
     */
    ScrollPane spBtnSauveProjet = new ScrollPane();
    spBtnSauveProjet.getStyleClass().add("menuBarreOutils");
    spBtnSauveProjet.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnSauveProjet.setPrefHeight(35);
    spBtnSauveProjet.setMaxHeight(35);
    spBtnSauveProjet.setPadding(new Insets(2));
    spBtnSauveProjet.setPrefWidth(35);

    HBox.setMargin(spBtnSauveProjet, new Insets(5, 15, 0, 0));
    ivSauveProjet = new ImageView(
            new Image("file:" + getStrRepertAppli() + File.separator + "images/sauveProjet.png"));
    spBtnSauveProjet.setContent(ivSauveProjet);
    Tooltip tltpSauverProjet = new Tooltip(rbLocalisation.getString("sauverProjet"));
    tltpSauverProjet.setStyle(getStrTooltipStyle());
    spBtnSauveProjet.setTooltip(tltpSauverProjet);
    hbBarreBouton.getChildren().add(spBtnSauveProjet);
    Separator sepImages = new Separator(Orientation.VERTICAL);
    sepImages.prefHeight(200);
    hbBarreBouton.getChildren().add(sepImages);
    ivSauveProjet.setDisable(true);
    ivSauveProjet.setOpacity(0.3);
    /*
     Bouton Ajoute Panoramique
     */
    ScrollPane spBtnAjoutePano = new ScrollPane();
    spBtnAjoutePano.getStyleClass().add("menuBarreOutils");
    spBtnAjoutePano.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnAjoutePano.setPrefHeight(35);
    spBtnAjoutePano.setMaxHeight(35);
    spBtnAjoutePano.setPadding(new Insets(2));
    spBtnAjoutePano.setPrefWidth(35);

    HBox.setMargin(spBtnAjoutePano, new Insets(5, 15, 0, 15));
    ivAjouterPano = new ImageView(
            new Image("file:" + getStrRepertAppli() + File.separator + "images/ajoutePanoramique.png"));
    spBtnAjoutePano.setContent(ivAjouterPano);
    Tooltip tltpAjouterPano = new Tooltip(rbLocalisation.getString("ajouterPanoramiques"));
    tltpAjouterPano.setStyle(getStrTooltipStyle());
    spBtnAjoutePano.setTooltip(tltpAjouterPano);
    hbBarreBouton.getChildren().add(spBtnAjoutePano);
    ivAjouterPano.setDisable(true);
    ivAjouterPano.setOpacity(0.3);

    /*
     Bouton Ajoute Panoramique
     */
    ScrollPane spBtnAjoutePlan = new ScrollPane();
    spBtnAjoutePlan.getStyleClass().add("menuBarreOutils");
    spBtnAjoutePlan.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnAjoutePlan.setPrefHeight(35);
    spBtnAjoutePlan.setMaxHeight(35);
    spBtnAjoutePlan.setPadding(new Insets(2));
    spBtnAjoutePlan.setPrefWidth(35);

    HBox.setMargin(spBtnAjoutePlan, new Insets(5, 15, 0, 15));
    setIvAjouterPlan(
            new ImageView(new Image("file:" + getStrRepertAppli() + File.separator + "images/ajoutePlan.png")));
    spBtnAjoutePlan.setContent(getIvAjouterPlan());
    Tooltip tltpAjouterPlan = new Tooltip(rbLocalisation.getString("ajouterPlan"));
    tltpAjouterPlan.setStyle(getStrTooltipStyle());
    spBtnAjoutePlan.setTooltip(tltpAjouterPlan);
    hbBarreBouton.getChildren().add(spBtnAjoutePlan);
    getIvAjouterPlan().setDisable(true);
    getIvAjouterPlan().setOpacity(0.3);

    /*
     Bouton Gnre
     */
    ScrollPane spBtnGenereVisite = new ScrollPane();
    spBtnGenereVisite.getStyleClass().add("menuBarreOutils");
    spBtnGenereVisite.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnGenereVisite.setPrefHeight(35);
    spBtnGenereVisite.setMaxHeight(35);
    spBtnGenereVisite.setPadding(new Insets(2));
    spBtnGenereVisite.setPrefWidth(70);

    HBox.setMargin(spBtnGenereVisite, new Insets(5, 15, 0, 0));
    ivVisiteGenere = new ImageView(
            new Image("file:" + getStrRepertAppli() + File.separator + "images/genereVisite.png"));
    spBtnGenereVisite.setContent(ivVisiteGenere);
    Tooltip tltpGenererVisite = new Tooltip(rbLocalisation.getString("genererVisite"));
    tltpGenererVisite.setStyle(getStrTooltipStyle());
    spBtnGenereVisite.setTooltip(tltpGenererVisite);
    hbBarreBouton.getChildren().add(spBtnGenereVisite);
    ivVisiteGenere.setDisable(true);
    ivVisiteGenere.setOpacity(0.3);
    Separator sepImages1 = new Separator(Orientation.VERTICAL);
    sepImages1.prefHeight(200);
    hbBarreBouton.getChildren().add(sepImages1);
    /*
     Bouton equi -> faces de  Cube
     */
    ScrollPane spBtnEqui2Cube = new ScrollPane();
    spBtnEqui2Cube.getStyleClass().add("menuBarreOutils");
    spBtnEqui2Cube.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnEqui2Cube.setPrefHeight(35);
    spBtnEqui2Cube.setMaxHeight(35);
    spBtnEqui2Cube.setPadding(new Insets(2));
    spBtnEqui2Cube.setPrefWidth(109);

    HBox.setMargin(spBtnEqui2Cube, new Insets(5, 15, 0, 250));
    ivEqui2Cube = new ImageView(
            new Image("file:" + getStrRepertAppli() + File.separator + "images/equi2cube.png"));
    spBtnEqui2Cube.setContent(ivEqui2Cube);
    Tooltip tltpEqui2Cube = new Tooltip(rbLocalisation.getString("outilsEqui2Cube"));
    tltpEqui2Cube.setStyle(getStrTooltipStyle());
    spBtnEqui2Cube.setTooltip(tltpEqui2Cube);
    hbBarreBouton.getChildren().add(spBtnEqui2Cube);

    /*
     Bouton faces de cube -> equi
     */
    ScrollPane spBtnCube2Equi = new ScrollPane();
    spBtnCube2Equi.getStyleClass().add("menuBarreOutils");
    spBtnCube2Equi.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
    spBtnCube2Equi.setPrefHeight(35);
    spBtnCube2Equi.setMaxHeight(35);
    spBtnCube2Equi.setPadding(new Insets(2));
    spBtnCube2Equi.setPrefWidth(109);

    HBox.setMargin(spBtnCube2Equi, new Insets(5, 25, 0, 0));
    ivCube2Equi = new ImageView(
            new Image("file:" + getStrRepertAppli() + File.separator + "images/cube2equi.png"));
    spBtnCube2Equi.setContent(ivCube2Equi);
    Tooltip tltpCube2Equi = new Tooltip(rbLocalisation.getString("outilsCube2Equi"));
    tltpCube2Equi.setStyle(getStrTooltipStyle());
    spBtnCube2Equi.setTooltip(tltpCube2Equi);
    hbBarreBouton.getChildren().add(spBtnCube2Equi);
    if (isMac()) {
        mbarPrincipal.setMaxHeight(0);
        hbBarreBouton.setTranslateY(-30);
    }
    vbMonPanneau.getChildren().addAll(mbarPrincipal, hbBarreBouton);
    vbRacine.getChildren().add(vbMonPanneau);
    mniNouveauProjet.setOnAction((e) -> {
        projetsNouveau();
    });
    mniChargeProjet.setOnAction((e) -> {
        try {
            try {
                projetCharge();

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

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    mniSauveProjet.setOnAction((e) -> {
        try {
            projetSauve();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    mniSauveSousProjet.setOnAction((e) -> {
        try {
            projetSauveSous();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    mniVisiteGenere.setOnAction((e) -> {
        try {
            genereVisite();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    mniFermerProjet.setOnAction((e) -> {
        try {
            projetsFermer();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    mniAjouterPano.setOnAction((e) -> {
        try {
            panoramiquesAjouter();

        } catch (InterruptedException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    getMniAjouterPlan().setOnAction((e) -> {
        planAjouter();
    });
    mniAPropos.setOnAction((e) -> {
        aideapropos();
    });
    mniAide.setOnAction((e) -> {
        AideDialogController.affiche();
    });

    mniChargerModele.setOnAction((e) -> {
        try {
            modeleCharger();

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

    mniSauverModele.setOnAction((e) -> {
        try {
            modeleSauver();

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

    mniCube2EquiTransformation.setOnAction((e) -> {
        transformationCube2Equi();
    });

    mniEqui2CubeTransformation.setOnAction((e) -> {
        transformationEqui2Cube();
    });

    mniOutilsBarre.setOnAction((e) -> {
        creerEditerBarre("");
    });
    mniOutilsDiaporama.setOnAction((e) -> {
        creerEditerDiaporama("");
    });
    mniOutilsLoupe.setOnAction((e) -> {
        e.consume();
        setAfficheLoupe(!isAfficheLoupe());
        apLoupe.setVisible(isAfficheLoupe());
        Point p = MouseInfo.getPointerInfo().getLocation();
        if (p.x < getiTailleLoupe() + 80 && p.y < getiTailleLoupe() + 160) {
            apLoupe.setLayoutX(ivImagePanoramique.getFitWidth() - getiTailleLoupe() + 5);
            apLoupe.setLayoutY(35);
            strPositLoupe = "droite";
        } else {
            apLoupe.setLayoutX(35);
            apLoupe.setLayoutY(35);
            strPositLoupe = "gauche";
        }
    });

    mniAffichageVisite.setOnAction((e) -> {
        tpEnvironnement.getSelectionModel().select(0);
    });
    mniAffichageInterface.setOnAction((e) -> {
        tpEnvironnement.getSelectionModel().select(1);
    });
    getMniAffichagePlan().setOnAction((e) -> {
        if (!tabPlan.isDisabled()) {
            tpEnvironnement.getSelectionModel().select(2);
        }
    });

    mniConfigTransformation.setOnAction((e) -> {
        try {
            ConfigDialogController cfg = new ConfigDialogController();
            cfg.afficheFenetre();

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

    spBtnNouvprojet.setOnMouseClicked((t) -> {
        projetsNouveau();
    });
    spBtnOuvrirProjet.setOnMouseClicked((t) -> {
        try {
            try {
                projetCharge();

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

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnSauveProjet.setOnMouseClicked((t) -> {
        try {
            projetSauve();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnAjoutePano.setOnMouseClicked((t) -> {
        try {
            panoramiquesAjouter();

        } catch (InterruptedException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnAjoutePlan.setOnMouseClicked((t) -> {
        planAjouter();
    });
    spBtnGenereVisite.setOnMouseClicked((t) -> {
        try {
            genereVisite();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
    spBtnEqui2Cube.setOnMouseClicked((t) -> {
        transformationEqui2Cube();
    });
    spBtnCube2Equi.setOnMouseClicked((t) -> {
        transformationCube2Equi();
    });

}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void init(final Stage primaryStage, final Container comp, final SplitPane splitpane,
        final TableView<Gene> genetable, final TableView<Function> upper, final TableView<GeneGroup> lower,
        final MenuBar menubar, final ToolBar toolbar, final ToolBar btoolbar) {
    geneset.user = System.getProperty("user.name");
    JavaFasta.user = geneset.user;/*from w  w  w  .  java2  s. c  o  m*/
    this.splitpane = splitpane;
    this.primaryStage = primaryStage;

    table = lower;
    gtable = genetable;
    //SerifyApplet.user = user;

    /*try {
       UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    } catch (ClassNotFoundException e) {
       e.printStackTrace();
    } catch (InstantiationException e) {
       e.printStackTrace();
    } catch (IllegalAccessException e) {
       e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
       e.printStackTrace();
    }*/

    String userhome = System.getProperty("user.home");
    boolean windows = false;
    try {
        InputStream isk = GeneSet.class.getClassLoader().getResourceAsStream("org/simmi/genesetkey");
        //Path gkey = Paths.get( url.toURI() );
        InputStream iskp = GeneSet.class.getClassLoader().getResourceAsStream("org/simmi/genesetkey.pub");
        //Path gkeypub = Paths.get( url.toURI() );

        Path gkeyssh = Paths.get(userhome);
        //Path gkeyssh = userpath.resolve(".ssh");
        if (!Files.exists(gkeyssh))
            Files.createDirectory(gkeyssh);
        Path gkeylocal = gkeyssh.resolve("org/simmi/genesetkey");
        Path gkeylocalpub = gkeyssh.resolve("org/simmi/genesetkey.pub");
        if (!Files.exists(gkeylocal) && isk != null) {
            Files.copy(isk, gkeylocal, StandardCopyOption.REPLACE_EXISTING);
        }
        if (!Files.exists(gkeylocalpub) && iskp != null) {
            Files.copy(iskp, gkeylocalpub);
        }

        Set<PosixFilePermission> poset = new HashSet<PosixFilePermission>();
        poset.add(PosixFilePermission.OWNER_READ);
        poset.add(PosixFilePermission.OWNER_WRITE);
        if (Files.exists(gkeylocal))
            Files.setPosixFilePermissions(gkeylocal, poset);
        if (Files.exists(gkeylocalpub))
            Files.setPosixFilePermissions(gkeylocalpub, poset);
    } catch (IOException e1) {
        e1.printStackTrace();
    } catch (UnsupportedOperationException e2) {
        windows = true;
        e2.printStackTrace();
    }

    if (windows) {
        File f = new File(userhome + "\\genesetkey");
        f.setExecutable(false, false);
        f.setWritable(false, false);
        f.setReadable(false, false);

        f.setWritable(true, true);
        f.setReadable(true, true);
    }

    this.comp = comp;
    selcomb = new ComboBox<>();
    searchcolcomb = new ComboBox<>();
    syncolorcomb = new ComboBox<>();

    searchcolcomb.getItems().add("Name");
    searchcolcomb.getItems().add("Symbol");
    searchcolcomb.getSelectionModel().select(0);

    setColors();

    JMenuBar jmenubar = new JMenuBar();
    Menu file = new Menu("File");

    MenuItem newitem = new MenuItem("New");
    newitem.setOnAction(actionEvent -> newFile());
    file.getItems().add(newitem);

    MenuItem openitem = new MenuItem("Open");
    openitem.setOnAction(actionEvent -> {
        try {
            importStuff();
        } catch (IOException e3) {
            e3.printStackTrace();
        } catch (UnavailableServiceException e3) {
            e3.printStackTrace();
        }
    });
    file.getItems().add(openitem);
    file.getItems().add(new SeparatorMenuItem());

    MenuItem importitem = new MenuItem("Import genomes");
    importitem.setOnAction(actionEvent -> fetchGenomes());
    file.getItems().add(importitem);

    MenuItem exportitem = new MenuItem("Export genomes");
    exportitem.setOnAction(actionEvent -> exportGenomes(geneset.speccontigMap));
    file.getItems().add(exportitem);

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

    MenuItem exportproteinitem = new MenuItem("Export protein sequences");
    exportproteinitem.setOnAction(actionEvent -> exportProteinSequences(geneset.genelist));
    file.getItems().add(exportproteinitem);

    MenuItem exportgeneitem = new MenuItem("Export gene clusters");
    exportgeneitem.setOnAction(actionEvent -> exportGeneClusters(geneset.allgenegroups));
    file.getItems().add(exportgeneitem);

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

    MenuItem quititem = new MenuItem("Quit");
    quititem.setOnAction(actionEvent -> System.exit(0));
    file.getItems().add(quititem);

    Menu edit = new Menu("Edit");
    MenuItem clustergenes = new MenuItem("Cluster genes");
    clustergenes.setOnAction(actionEvent -> {
        //fxpanel.setScene( null );
        /*Platform.runLater(new Runnable() {
              @Override
              public void run() {
          Label label1 = new Label("Id:");
              tb1 = new TextField("0.5");
              Label label2 = new Label("Len:");
              tb2 = new TextField("0.5");
                      
              VBox vbox = new VBox();
              HBox hbox1 = new HBox();
              hbox1.getChildren().addAll( label1, tb1 );
              HBox hbox2 = new HBox();
              hbox2.getChildren().addAll( label2, tb2 );
                      
              epar = new TextField();
              vbox.getChildren().add( epar );
                      
              vbox.getChildren().addAll( hbox1, hbox2 );
              if( fxs == null ) fxs = new Scene( vbox );
              fxs.setRoot( vbox );
                      
              fxpanel.setScene( fxs );
              }
        });*/

        JPanel panel = new JPanel();
        GridBagLayout grid = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        panel.setLayout(grid);

        /*JLabel label1 = new JLabel("Id:");
        JTextField tb1 = new JTextField("0.5");
        JLabel label2 = new JLabel("Len:");
        JTextField tb2 = new JTextField("0.5");
                
        Dimension d = new Dimension( 300, 30 );
        JTextField epar = new JTextField();
        epar.setSize( d );
        epar.setPreferredSize( d );
                
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 1;
        c.gridheight = 1;
                
        c.gridx = 0;
        c.gridy = 0;
        panel.add( label1, c );
        c.gridx = 1;
        c.gridy = 0;
        panel.add( tb1, c );
        c.gridx = 0;
        c.gridy = 1;
        panel.add( label2, c );
        c.gridx = 1;
        c.gridy = 1;
        panel.add( tb2, c );
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 2;
        panel.add( epar, c );
                
        JOptionPane.showMessageDialog(comp, new Object[] {panel}, "Clustering parameters", JOptionPane.PLAIN_MESSAGE );*/

        /*if( tb1 != null ) {
           float id = Float.parseFloat( tb1.getText() );
           float len = Float.parseFloat( tb2.getText() );
           String expar = epar.getText();
                   
           tb1 = null;
           tb2 = null;
           epar = null;*/

        Set<String> species = getSelspec(null, geneset.getSpecies(), null);
        geneset.clusterGenes(species, false);
        //}
    });
    MenuItem alignclusters = new MenuItem("Align clusters");
    alignclusters.setOnAction(actionEvent -> {
        try {
            String OS = System.getProperty("os.name").toLowerCase();

            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr);
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            //s.makeBlastCluster(zipfilesystem.getPath("/"), p, 1);
            Path aldir = geneset.zipfilesystem.getPath("aligned");
            final Path aligneddir = Files.exists(aldir) ? aldir : Files.createDirectory(aldir);

            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try {
                        geneset.zipfilesystem.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            NativeRun nrun = new NativeRun(run);
            //ExecutorService es = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() );

            Object[] cont = new Object[3];

            Collection<GeneGroup> ggset;
            ObservableList<GeneGroup> ogg = table.getSelectionModel().getSelectedItems();
            ggset = new HashSet<GeneGroup>();
            if (ogg.size() == 0) {
                for (GeneGroup gg : geneset.allgenegroups) {
                    //GeneGroup gg = allgenegroups.get(table.convertRowIndexToModel(r));
                    //gg.getCommonTag()
                    if (gg != null && gg.getCommonTag() == null && gg.size() > 1)
                        ggset.add(gg);
                }
            } else {
                for (GeneGroup gg : ogg) {
                    //GeneGroup gg = geneset.allgenegroups.get(table.convertRowIndexToModel(r));
                    //gg.getCommonTag()
                    if (gg != null && gg.getCommonTag() == null && gg.size() > 1)
                        ggset.add(gg);
                }
            }

            //int i = 0;
            List commandsList = new ArrayList();
            for (GeneGroup gg : ggset) {
                String fasta = gg.getFasta(true);
                String[] cmds = new String[] {
                        OS.indexOf("mac") >= 0 ? "/usr/local/bin/mafft" : "/usr/bin/mafft", "-" };
                Object[] paths = new Object[] { fasta.getBytes(), aligneddir.resolve(gg.getCommonId() + ".aa"),
                        null };
                commandsList.add(paths);
                commandsList.add(Arrays.asList(cmds));

                //if( i++ > 5000 ) break;
            }
            nrun.runProcessBuilder("Running mafft", commandsList, cont, true, run, false);
        } catch (IOException e1) {
            if (geneset.zipfilesystem != null) {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
            e1.printStackTrace();
        }
    });

    MenuItem sharenumaction = new MenuItem("Update share numbers");
    sharenumaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        Set<String> specs = getSelspec(GeneSetHead.this, geneset.specList, null);
        geneset.updateShareNum(specs);
    }));

    MenuItem importgeneclusteringaction = new MenuItem("Import gene clustering");
    importgeneclusteringaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        JPanel panel = new JPanel();
        GridBagLayout grid = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        panel.setLayout(grid);

        JLabel label1 = new JLabel("Id:");
        JTextField tb11 = new JTextField("0.5");
        JLabel label2 = new JLabel("Len:");
        JTextField tb21 = new JTextField("0.5");

        Dimension d = new Dimension(300, 30);
        JTextField epar1 = new JTextField();
        epar1.setSize(d);
        epar1.setPreferredSize(d);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 1;
        c.gridheight = 1;

        c.gridx = 0;
        c.gridy = 0;
        panel.add(label1, c);
        c.gridx = 1;
        c.gridy = 0;
        panel.add(tb11, c);
        c.gridx = 0;
        c.gridy = 1;
        panel.add(label2, c);
        c.gridx = 1;
        c.gridy = 1;
        panel.add(tb21, c);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 2;
        panel.add(epar1, c);

        JOptionPane.showMessageDialog(comp, new Object[] { panel }, "Clustering parameters",
                JOptionPane.PLAIN_MESSAGE);

        float id = Float.parseFloat(tb11.getText());
        float len = Float.parseFloat(tb21.getText());

        //JFileChooser fc = new JFileChooser();
        //if( fc.showOpenDialog( GeneSetHead.this ) == JFileChooser.APPROVE_OPTION ) {
        Serifier s = new Serifier();
        //s.mseq = aas;
        for (String gk : geneset.refmap.keySet()) {
            Gene g = geneset.refmap.get(gk);
            if (g.tegeval.getAlignedSequence() != null)
                System.err.println(g.tegeval.getAlignedSequence().getName());
            s.mseq.put(gk, g.tegeval.getAlignedSequence());
        }

        Map<String, String> idspec = new HashMap<String, String>();
        for (String idstr : geneset.refmap.keySet()) {
            if (idstr.contains(" ")) {
                System.err.println("coooonnnnnni " + idstr);
            }

            Gene gene = geneset.refmap.get(idstr);
            idspec.put(idstr, gene.getSpecies());
        }
        //Sequences seqs = new Sequences(user, name, type, path, nseq)
        try {
            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr);
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

            Path root = geneset.zipfilesystem.getPath("/");
            Path p = geneset.zipfilesystem.getPath("cluster.blastout"); //root.resolve("culster.blastout");

            List<Set<String>> cluster = geneset.uclusterlist == null ? new ArrayList<>()
                    : new ArrayList<>(geneset.uclusterlist);
            s.makeBlastCluster(root, p, 1, id, len, idspec, cluster, geneset.refmap);

            System.err.println(cluster.get(0));
            if (geneset.uclusterlist != null)
                System.err.println(geneset.uclusterlist.get(0));

            geneset.zipfilesystem.close();
        } catch (IOException e1) {
            if (geneset.zipfilesystem != null) {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
            e1.printStackTrace();
        }
    }));
    MenuItem importgenesymbolaction = new MenuItem("Import gene symbols");
    importgenesymbolaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        JFileChooser fc = new JFileChooser();
        if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
            try {
                Map<String, String> env = new HashMap<>();
                env.put("create", "true");
                //Path path = zipfile.toPath();
                String uristr = "jar:" + geneset.zippath.toUri();
                geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

                Path nf = geneset.zipfilesystem.getPath("/smap_short.txt");
                BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE);

                File f = fc.getSelectedFile();
                InputStream is = new FileInputStream(f);
                if (f.getName().endsWith(".gz"))
                    is = new GZIPInputStream(is);
                geneset.uni2symbol(new InputStreamReader(is), bw, geneset.unimap);

                bw.close();
                //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
                geneset.zipfilesystem.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));

    MenuItem importcazyaction = new MenuItem("Import Cazy");
    importcazyaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        JFileChooser fc = new JFileChooser();
        if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedReader rd = Files.newBufferedReader(fc.getSelectedFile().toPath());
                geneset.loadcazymap(geneset.cazymap, rd);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));

    MenuItem gene2refseqaction = new MenuItem("Gene 2 refseq");
    gene2refseqaction.setOnAction(actionEvent -> {
        try {
            TextField tf = new TextField();
            tf.setText("ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2refseq.gz");
            Dialog<Path> dialog = new Dialog();
            dialog.getDialogPane().setContent(tf);
            dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
            dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
            dialog.setResultConverter(param -> param.getButtonData().isCancelButton() ? null
                    : Paths.get(URI.create(tf.getText())));
            Optional<Path> opath = dialog.showAndWait();

            if (opath.isPresent()) {
                Map<String, String> env = new HashMap<>();
                env.put("create", "true");
                //Path path = zipfile.toPath();
                String uristr = "jar:" + geneset.zippath.toUri();
                geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/);
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

                Path path = opath.get();
                InputStream is = path.toUri().toURL().openStream();
                if (path.getFileName().toString().endsWith(".gz")) {
                    is = new GZIPInputStream(is);
                }
                Path nf = geneset.zipfilesystem.getPath("/org/simmi/gene2refseq_short.txt");
                BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                geneset.idMapping(new InputStreamReader(is), bw, 5, 1, geneset.refmap, null, geneset.gimap);
                bw.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                geneset.zipfilesystem.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    MenuItem functionmappingaction = new MenuItem("Function mapping");
    functionmappingaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        final JTextField tf = new JTextField();
        JButton btn = new JButton("File");
        JComponent comp2 = new JComponent() {
        };
        comp2.setLayout(new BorderLayout());
        comp2.add(tf);
        comp2.add(btn, BorderLayout.EAST);
        tf.setText("http://130.208.252.239/data/sp2go.txt.gz");

        final File[] file2 = new File[1];
        btn.addActionListener(e -> {
            JFileChooser fc = new JFileChooser();
            if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
                file2[0] = fc.getSelectedFile();
                try {
                    tf.setText(fc.getSelectedFile().toURI().toURL().toString());
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
            }
        });

        try {
            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            //Path path = zipfile.toPath();
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

            Path nf = geneset.zipfilesystem.getPath("/org/simmi/sp2go_short.txt");
            BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

            JOptionPane.showMessageDialog(GeneSetHead.this, comp2);

            final JDialog dialog = new JDialog();
            dialog.setTitle("Function mapping");
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setSize(400, 300);

            comp2 = new JComponent() {
            };
            comp2.setLayout(new BorderLayout());

            final JTextArea ta = new JTextArea();
            /*final InputStream fis;
            if( file[0] != null ) fis = new FileInputStream( file[0] );
            else {
            JTextField host = new JTextField("localhost");
            JOptionPane.showMessageDialog(null, host);
                    
            String username = System.getProperty("user.name");
            String hostname = host.getText();
                    
            List<String> commandsList = Arrays.asList( new String[] {"ssh",username+"@"+hostname,"cat",tf.getText()} );
            ProcessBuilder pb = new ProcessBuilder( commandsList );
            Process p = pb.start();
                    
            for( Object commands : commandsList ) {
                if( commands instanceof List ) {
                    for( Object cmd : (List)commands ) {
                        ta.append(cmd+" ");
                    }
                    ta.append("\n");
                } else {
                    ta.append(commands+" ");
                }
            }
            ta.append("\n");
                    
            fis = p.getInputStream();
            }*/

            final JProgressBar pbar = new JProgressBar();
            final Thread t = new Thread() {
                public void run() {
                    try {
                        URL url = new URL(tf.getText());
                        InputStream fis = url.openStream();

                        BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(fis)));
                        //if( unimap != null ) unimap.clear();
                        //unimap = idMapping(new InputStreamReader(is), bw, 2, 0, refmap, genmap, gimap);
                        geneset.funcMappingUni(br, geneset.unimap, bw);

                        fis.close();
                        bw.close();

                        try {
                            geneset.zipfilesystem.close();
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }
                        ;

                        pbar.setIndeterminate(false);
                        pbar.setEnabled(false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            ta.setEditable(false);
            final JScrollPane sp = new JScrollPane(ta);

            dialog.add(comp2);
            comp2.add(pbar, BorderLayout.NORTH);
            comp2.add(sp, BorderLayout.CENTER);
            pbar.setIndeterminate(true);

            t.start();
            /*okokdialog.addWindowListener( new WindowListener() {
                    
            @Override
            public void windowOpened(WindowEvent e) {}
                    
            @Override
            public void windowIconified(WindowEvent e) {}
                    
            @Override
            public void windowDeiconified(WindowEvent e) {}
                    
            @Override
            public void windowDeactivated(WindowEvent e) {}
                    
            @Override
            public void windowClosing(WindowEvent e) {}
                    
            @Override
            public void windowClosed(WindowEvent e) {
                if( pbar.isEnabled() ) {
                    pbar.setIndeterminate( false );
                    pbar.setEnabled( false );
                }
            }
                    
            @Override
            public void windowActivated(WindowEvent e) {}
            });*/
            dialog.setVisible(true);
            //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }));
    MenuItem importidmappingaction = new MenuItem("Import idmapping");
    importidmappingaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        final JTextField tf = new JTextField();
        JButton btn = new JButton("File");
        JComponent comp2 = new JComponent() {
        };
        comp2.setLayout(new BorderLayout());
        comp2.add(tf);
        comp2.add(btn, BorderLayout.EAST);
        tf.setText(
                "ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/idmapping/idmapping.dat.gz");

        final File[] file2 = new File[1];
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                if (fc.showOpenDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
                    file2[0] = fc.getSelectedFile();
                    try {
                        tf.setText(fc.getSelectedFile().toURI().toURL().toString());
                    } catch (MalformedURLException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });

        JOptionPane.showMessageDialog(GeneSetHead.this, comp2);

        //Thread t = new Thread() {
        //   public void run() {
        try {
            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            //Path path = zipfile.toPath();
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);

            Path nf = geneset.zipfilesystem.getPath("/org/simmi/idmapping_short.dat");
            final BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

            final JDialog dialog = new JDialog();
            dialog.setTitle("Id mapping");
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setSize(400, 300);

            comp2 = new JComponent() {
            };
            comp2.setLayout(new BorderLayout());

            final JTextArea ta = new JTextArea();

            /*final InputStream fis;
            if( file[0] != null ) fis = new FileInputStream( file[0] );
            else {
            /*Object[] cont = new Object[3];
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        bw.close();
                        geneset.zipfilesystem.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };*
                    
            JTextField host = new JTextField("localhost");
            JOptionPane.showMessageDialog(null, host);
                    
            String username = System.getProperty("user.name");
            String hostname = host.getText();
                    
            List<String> commandsList = Arrays.asList( new String[] {"ssh",username+"@"+hostname,"cat",tf.getText()} );
            ProcessBuilder pb = new ProcessBuilder( commandsList );
            Process p = pb.start();
                    
            for( Object commands : commandsList ) {
                if( commands instanceof List ) {
                    for( Object cmd : (List)commands ) {
                        ta.append(cmd+" ");
                    }
                    ta.append("\n");
                } else {
                    ta.append(commands+" ");
                }
            }
            ta.append("\n");
                    
            fis = p.getInputStream();
            }*/

            final JProgressBar pbar = new JProgressBar();
            final Thread t = new Thread() {
                public void run() {
                    try {
                        URL url = new URL(tf.getText());
                        InputStream fis = url.openStream();
                        InputStream is = new GZIPInputStream(fis);
                        if (geneset.unimap != null)
                            geneset.unimap.clear();
                        geneset.unimap = geneset.idMapping(new InputStreamReader(is), bw, 2, 0, geneset.refmap,
                                geneset.genmap, geneset.gimap);
                        is.close();
                        fis.close();
                        bw.close();

                        try {
                            geneset.zipfilesystem.close();
                        } catch (Exception ep) {
                            ep.printStackTrace();
                        }
                        ;

                        pbar.setIndeterminate(false);
                        pbar.setEnabled(false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            ta.setEditable(false);
            final JScrollPane sp = new JScrollPane(ta);

            dialog.add(comp2);
            comp2.add(pbar, BorderLayout.NORTH);
            comp2.add(sp, BorderLayout.CENTER);
            pbar.setIndeterminate(true);

            t.start();

            /*System.err.println( "about to run" );
            for( Object commands : commandsList ) {
                if( commands instanceof List ) {
                    for( Object c : (List)commands ) {
                        System.err.print( c+" " );
                    }
                    System.err.println();
                } else {
                    System.err.print( commands+" " );
                }
            }
            System.err.println();*/

            /*okokdialog.addWindowListener( new WindowListener() {
                    
            @Override
            public void windowOpened(WindowEvent e) {}
                    
            @Override
            public void windowIconified(WindowEvent e) {}
                    
            @Override
            public void windowDeiconified(WindowEvent e) {}
                    
            @Override
            public void windowDeactivated(WindowEvent e) {}
                    
            @Override
            public void windowClosing(WindowEvent e) {}
                    
            @Override
            public void windowClosed(WindowEvent e) {
                if( pbar.isEnabled() ) {
                    /*String result = ta.getText().trim();
                    if( run != null ) {
                        cont[0] = null;
                        cont[1] = result;
                        cont[2] = new Date( System.currentTimeMillis() ).toString();
                        run.run();
                    }*
                    
                    pbar.setIndeterminate( false );
                    pbar.setEnabled( false );
                }
            }
                    
            @Override
            public void windowActivated(WindowEvent e) {}
            });*/
            dialog.setVisible(true);

            /*NativeRun nrun = new NativeRun();
            nrun.runProcessBuilder("Idmapping", Arrays.asList( tf.getText().split(" ") ), run, cont, false);
            ProcessBuilder pb = new ProcessBuilder( tf.getText().split(" ") );
            Process p = pb.start();
            fis = p.getInputStream();
            }*/

            //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
        } catch (IOException e1) {
            e1.printStackTrace();
            try {
                geneset.zipfilesystem.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            ;
        }
        //   }
        //};
        //t.start();
        //}
    }));
    MenuItem cogblastaction = new MenuItem("Cog blast");
    cogblastaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        Set<String> species = getSelspec(null, geneset.getSpecies(), null);

        if (species != null && species.size() > 0)
            Platform.runLater(() -> cogBlastDlg(species));
    }));
    MenuItem unresolvedblastaction = new MenuItem("Unresolved blast");
    unresolvedblastaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        try {
            Set<String> species = getSelspec(null, geneset.getSpecies(), null);

            StringWriter sb = new StringWriter();
            Path dbPath = Paths.get("/data/nr");
            ObservableList<Gene> genes = gtable.getSelectionModel().getSelectedItems();
            if (genes.size() > 0) {
                if (isGeneview()) {
                    for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                        //int i = table.convertRowIndexToModel(r);
                        //Gene g = geneset.genelist.get(i);
                        Sequence gs = g.tegeval.getProteinSequence();
                        gs.setName(g.id);
                        gs.writeSequence(sb);
                    }
                } else {
                    for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                        //int i = table.convertRowIndexToModel(r);
                        //GeneGroup gg = geneset.allgenegroups.get(i);
                        Gene g = null;
                        for (Gene gene : gg.genes) {
                            g = gene;
                            break;
                        }
                        Sequence gs = g.tegeval.getProteinSequence();
                        gs.setName(g.id);
                        gs.writeSequence(sb);
                    }
                }
            } else {
                for (Gene g : geneset.genelist) {
                    if (g.getTag() == null || g.getTag().equalsIgnoreCase("gene")) {
                        if (species.contains(g.getSpecies())) {
                            Sequence gs = g.tegeval.getProteinSequence();
                            gs.setName(g.id);
                            gs.writeSequence(sb);

                            /*sb.append(">" + g.id + "\n");
                            for (int i = 0; i < gs.length(); i += 70) {
                            sb.append( gs.substring(i, Math.min( i + 70, gs.length() )) + "\n");
                            }*/
                        }
                    }
                }
            }

            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            Path resPath = geneset.zipfilesystem.getPath("/unresolved.blastout");

            NativeRun nrun = new NativeRun();
            SerifyApplet.blastpRun(nrun, sb.getBuffer(), dbPath, resPath, "-evalue 0.00001", null, true,
                    geneset.zipfilesystem, geneset.user, primaryStage);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }));

    MenuItem importbiosystemsaction = new MenuItem("Import biosystems");
    importbiosystemsaction.setOnAction(actionEvent -> {
        Dialog<Map<String, Set<String>>> dialog = new Dialog();

        TextField gene = new TextField();
        TextField biosys = new TextField();

        gene.setText("ftp://ftp.ncbi.nlm.nih.gov/pub/biosystems/biosystems.20160519/biosystems_gene_all.gz");
        biosys.setText("ftp://ftp.ncbi.nlm.nih.gov/pub/biosystems/biosystems.20160519/bsid2info.gz");

        VBox duo = new VBox();
        duo.getChildren().add(gene);
        duo.getChildren().add(biosys);

        dialog.getDialogPane().setContent(duo);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
        dialog.setResultConverter(param -> {
            if (!param.getButtonData().isCancelButton()) {
                Map<String, Set<String>> result = null;
                Set<String> geneidset = geneset.genelist.stream().map(g -> g.genid).collect(Collectors.toSet());
                try {
                    InputStream p = new URI(gene.getText()).toURL().openStream();
                    InputStream b = new URI(biosys.getText()).toURL().openStream();

                    if (gene.getText().endsWith(".gz"))
                        p = new GZIPInputStream(p);
                    if (biosys.getText().endsWith(".gz"))
                        b = new GZIPInputStream(b);

                    Map<String, List<String[]>> group = new BufferedReader(new InputStreamReader(p)).lines()
                            .map(l -> l.split("\t")).filter(s -> geneidset.contains(s[1]))
                            .collect(Collectors.groupingBy(s -> s[1]));
                    Set<String> bsids = group.entrySet().stream().flatMap(e -> e.getValue().stream())
                            .map(s -> s[0]).collect(Collectors.toSet());
                    Map<String, String> bsid2name = new BufferedReader(new InputStreamReader(b)).lines()
                            .map(s -> s.split("\t")).filter(s -> bsids.contains(s[0]))
                            .collect(Collectors.toMap(s -> s[0], s -> s[2] + ":" + s[3]));
                    result = group.entrySet().stream()
                            .collect(Collectors.toMap(s -> s.getKey(), s -> s.getValue().stream()
                                    .map(sub -> bsid2name.get(sub[0])).collect(Collectors.toSet())));
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                //Path p = Paths.get(gene.getText());
                //Path b = Paths.get(biosys.getText());
                return result;
            }
            return null;
        });
        Optional<Map<String, Set<String>>> od = dialog.showAndWait();

        if (od.isPresent()) {
            geneset.biosystemsmap = od.get();
            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                Path resPath = geneset.zipfilesystem.getPath("/biosystems.txt");
                BufferedWriter bw = Files.newBufferedWriter(resPath, StandardOpenOption.TRUNCATE_EXISTING);
                geneset.biosystemsmap.entrySet().stream().forEach(e -> {
                    try {
                        bw.write(e.getKey() + "\t" + e.getValue().stream().collect(Collectors.joining(";"))
                                + "\n");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                });
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    MenuItem importkeggpathwayaction = new MenuItem("Import kegg pathways");
    importkeggpathwayaction.setOnAction(actionEvent -> {
        Set<String> keggids = new HashSet<>();
        for (Gene g : geneset.genelist) {
            if (g.keggid != null) {
                int i = g.keggid.indexOf(':');
                if (i > 0) {
                    keggids.add(g.keggid.substring(0, i));
                }
            }
        }
        System.err.println(keggids);

        JTextField tf = new JTextField("http://130.208.252.239/organisms/");
        JOptionPane.showMessageDialog(null, tf);

        Map<String, String> env = new HashMap<>();
        env.put("create", "true");

        Path rootp = null;
        try {
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
        } catch (Exception ee) {
            ee.printStackTrace();
        }

        for (Path root : geneset.zipfilesystem.getRootDirectories()) {
            rootp = root;
            break;
        }

        for (String kegg : keggids) {
            try {
                URL url = new URL(tf.getText() + kegg + ".tar.gz");
                InputStream is = url.openStream();
                GZIPInputStream gz = new GZIPInputStream(is);

                TarArchiveInputStream tar = new TarArchiveInputStream(gz);
                TarArchiveEntry tae = (TarArchiveEntry) tar.getNextEntry();
                while (tae != null) {
                    geneset.traverseTar(tar, tae, rootp);

                    tae = (TarArchiveEntry) tar.getNextEntry();
                }

                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        try {
            geneset.zipfilesystem.close();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
        ;
    });

    edit.getItems().add(clustergenes);
    edit.getItems().add(alignclusters);
    edit.getItems().add(new SeparatorMenuItem());
    edit.getItems().add(sharenumaction);
    edit.getItems().add(importgeneclusteringaction);
    edit.getItems().add(importgenesymbolaction);
    edit.getItems().add(importcazyaction);
    edit.getItems().add(functionmappingaction);
    edit.getItems().add(importidmappingaction);
    edit.getItems().add(gene2refseqaction);
    edit.getItems().add(importbiosystemsaction);
    edit.getItems().add(importkeggpathwayaction);
    edit.getItems().add(new SeparatorMenuItem());
    edit.getItems().add(cogblastaction);
    edit.getItems().add(unresolvedblastaction);

    Menu view = new Menu("View");
    gb = new RadioMenuItem("Genes");
    gb.setOnAction(actionEvent -> {
        splitpane.getItems().remove(table);
        splitpane.getItems().add(0, gtable);
        //table.setModel( defaultModel );
    });
    view.getItems().add(gb);
    ggb = new RadioMenuItem("Gene groups");
    ggb.setOnAction(actionEvent -> {
        splitpane.getItems().remove(gtable);
        splitpane.getItems().add(0, table);
        //table.setModel( groupModel );
    });

    ToggleGroup bg = new ToggleGroup();
    gb.setToggleGroup(bg);
    ggb.setToggleGroup(bg);
    //ButtonGroup   bg = new ButtonGroup();
    //bg.add( gb );
    //bg.add( ggb );

    ggb.setSelected(true);
    view.getItems().add(ggb);
    ActionCollection.addAll(view, geneset.clusterMap, GeneSetHead.this, geneset.speccontigMap, table, comp,
            geneset.cs);

    Menu help = new Menu("Help");
    MenuItem about = new MenuItem("About");
    about.setOnAction(actionEvent -> SwingUtilities
            .invokeLater(() -> JOptionPane.showMessageDialog(comp, "CompGen 1.0")));
    help.getItems().add(about);

    MenuItem test = new MenuItem("Test");
    test.setOnAction(actionEvent -> {
        /*for( Gene g : geneset.genelist ) {
           Sequence seq = g.tegeval.getContig();
           if( seq == null ) {
          System.err.println();
           }
        }*/

        for (String spec : geneset.speccontigMap.keySet()) {
            if (spec.contains("RAST")) {
                List<Sequence> lseq = geneset.speccontigMap.get(spec);
                for (Sequence seq : lseq) {
                    for (Annotation a : seq.getAnnotations()) {
                        System.err.println(a.getGene().getGeneGroup().species);
                        /*Sequence tseq = a.getContig();
                        if( tseq == null ) {
                           System.err.println();
                        }*/
                    }
                }
            }
        }

        /*for( GeneGroup gg : allgenegroups ) {
           if( gg.species.size() > 1 ) {
          System.err.println( gg.species );
           }
        }*/
    });
    help.getItems().add(test);
    help.getItems().add(new SeparatorMenuItem());
    MenuItem runserver = new MenuItem("Run server");
    runserver.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JSpinner spin = new JSpinner();
                JOptionPane.showMessageDialog(GeneSetHead.this, spin, "Port", JOptionPane.QUESTION_MESSAGE);
                try {
                    geneset.cs = WSServer.startServer(GeneSetHead.this, (Integer) spin.getValue());
                } catch (UnknownHostException e1) {
                    e1.printStackTrace();
                }
            }

        });
    });
    help.getItems().add(runserver);
    help.getItems().add(new SeparatorMenuItem());

    CheckMenuItem cbmi = new CheckMenuItem("Use geneset user");
    help.getItems().add(cbmi);

    cbmi.setOnAction(actionEvent -> {
        if (cbmi.isSelected()) {
            geneset.user = "geneset";
        } else
            geneset.user = System.getProperty("user.name");

        JavaFasta.user = geneset.user;
        if (geneset.currentSerify != null)
            geneset.currentSerify.user = geneset.user;
    });

    help.getItems().add(new SeparatorMenuItem());
    MenuItem helptut = new MenuItem("Help & Tutorial");
    helptut.setOnAction(actionEvent -> {
        try {
            Desktop.getDesktop().browse(new URI("http://thermusgenes.appspot.com/pancore.html"));
        } catch (IOException | URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    help.getItems().add(helptut);

    Menu sequencemenu = new Menu("Sequence");
    MenuItem showgroupseq = new MenuItem("Show group sequences");
    showgroupseq.setOnAction(actionEvent -> {
        //JTextArea textarea = new JTextArea();
        //JScrollPane scrollpane = new JScrollPane(textarea);

        /*try {
           if (clipboardService == null)
          clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
           Action action = new CopyAction("Copy", null, "Copy data", new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
           textarea.getActionMap().put("copy", action);
           grabFocus = true;
        } catch (Exception ee) {
           ee.printStackTrace();
           System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }
                
        textarea.setDragEnabled(true);*/

        JFrame frame = null;
        if (geneset.currentSerify == null) {
            frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            frame.setSize(400, 300);

            Map<String, String> env = new HashMap<String, String>();
            //Path path = zipfile.toPath();
            String uristr = "jar:" + geneset.zippath.toUri();
            geneset.zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            SerifyApplet sa = new SerifyApplet(geneset.zipfilesystem);
            sa.init(frame, null, geneset.user);
            //frame.add( )
            geneset.currentSerify = sa;
        } /* else frame = (JFrame)currentSerify.cnt;*/

        String[] farr = new String[] { "o.profundus", "mt.silvanus", "mt.ruber", "m.hydrothermalis",
                "t.thermophilus_SG0_5JP17_16", "t.thermophilusJL18", "t.thermophilusHB8", "t.thermophilusHB27",
                "t.scotoductusSA01", "t.scotoductus4063", "t.scotoductus1572", "t.scotoductus2101",
                "t.scotoductus2127", "t.scotoductus346", "t.scotoductus252", "t.antranikiani", "t.kawarayensis",
                "t.brockianus", "t.igniterrae", "t.eggertsoni", "t.RLM", "t.oshimai_JL2", "t.oshimai",
                "t.filiformis", "t.arciformis", "t.islandicus", "t.aquaticus", "t.spCCB" };

        Map<Integer, String> ups = new HashMap<Integer, String>();
        Set<Integer> stuck = new HashSet<Integer>();
        Map<Integer, List<Tegeval>> ups2 = new HashMap<Integer, List<Tegeval>>();
        //int[] rr = table.getSelectedRows();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            //int cr = table.convertRowIndexToModel(r);
            //Gene gg = geneset.genelist.get(cr);
            if (gg.getSpecies() != null) {
                if (gg.genid != null && gg.genid.length() > 0) {
                    ups.put(gg.getGroupIndex(), gg.name);
                    stuck.add(gg.getGroupIndex());
                }
                if (!stuck.contains(gg.getGroupIndex())) {
                    if (!ups.containsKey(gg.getGroupIndex())
                            || !(gg.name.contains("unnamed") || gg.name.contains("hypot")))
                        ups.put(gg.getGroupIndex(), gg.name);
                }

                List<Tegeval> tlist;
                if (ups2.containsKey(gg.getGroupIndex()))
                    tlist = ups2.get(gg.getGroupIndex());
                else {
                    tlist = new ArrayList<Tegeval>();
                    ups2.put(gg.getGroupIndex(), tlist);
                }

                //Set<String>    specs = new HashSet<String>();
                //textarea.append(gg.name + ":\n");
                //for (String sp : gg.species.keySet()) {
                int count = 0;
                for (String sp : farr) {
                    //Teginfo stv = gg.species.equals(sp) ? gg.teginfo : null;

                    if (gg.getSpecies().equals(sp))
                        tlist.add(gg.tegeval);
                    /*for( String key : gg.species.keySet() ) {
                       if( key.contains("JL2") ) {
                          System.err.println( " erm " + key );
                       }
                    }*/
                    /*if( stv == null && gg.species.size() == 28 ) {
                       System.err.println( gg.species );
                       System.err.println( sp );
                    }*/
                    //System.err.println( gg.species.keySet() );
                    /*if( stv == null ) {
                       //System.err.println( sp );
                    } else {
                       count++;
                       //specs.add( sp );
                       for (Tegeval tv : stv.tset) {
                          tlist.add( tv );
                          /*textarea.append(">" + tv.cont + " " + tv.teg + " " + tv.eval + "\n");
                          if (tv.dna != null) {
                      for (int i = 0; i < tv.dna.length(); i += 70) {
                         textarea.append(tv.dna.gg.speciessubstring(i, Math.min(i + 70, tv.dna.length())) + "\n");
                      }
                          }*
                       }
                    }*/
                }
                //if( count < gg.species.size() ) {
                //   System.err.println( gg.species );
                //   System.err.println();
                //}
                //if( specs.size() < 28 ) System.err.println("mu " + specs);
            }
        }

        try {
            StringWriter sb = new StringWriter();
            for (int gi : ups.keySet()) {
                String name = ups.get(gi);
                List<Tegeval> tlist = ups2.get(gi);

                sb.append(name.replace('/', '-') + ":\n");
                if (tlist.size() < 28) {
                    for (Tegeval tv : tlist) {
                        System.err.println(tv.name);
                    }
                    System.err.println();
                }
                for (Tegeval tv : tlist) {
                    Sequence ps = tv.getProteinSequence();
                    ps.setName(tv.name.substring(0, tv.name.indexOf('_')));
                    ps.writeSequence(sb);
                    /*sb.append(">" + tv.name.substring(0, tv.name.indexOf('_')) + "\n");
                    for (int i = 0; i < ps.length(); i += 70) {
                       sb.append( ps.substring(i, Math.min(i + 70, tv.getProteinLength() )) + "\n");
                    }*/
                }
            }

            geneset.currentSerify.addSequences("uh", new StringReader(sb.toString()), Paths.get("/"), null);
        } catch (URISyntaxException | IOException e1) {
            e1.printStackTrace();
        }
        frame.setVisible(true);
    });
    sequencemenu.getItems().add(showgroupseq);

    MenuItem showgroupdnaseq = new MenuItem("Show group DNA sequences");
    showgroupdnaseq.setOnAction(actionEvent -> {
        final JTextArea textarea = new JTextArea();
        JScrollPane scrollpane = new JScrollPane(textarea);

        try {
            if (clipboardService == null)
                clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
            Action action = new CopyAction("Copy", null, "Copy data",
                    new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
            textarea.getActionMap().put("copy", action);
            grabFocus = true;
        } catch (Exception ee) {
            ee.printStackTrace();
            System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }

        textarea.setDragEnabled(true);

        try {
            final DataFlavor df = new DataFlavor("text/plain;charset=utf-8");
            TransferHandler th = new TransferHandler() {
                /**
                 * 
                 */
                private static final long serialVersionUID = 1L;

                public int getSourceActions(JComponent c) {
                    return TransferHandler.COPY_OR_MOVE;
                }

                public boolean canImport(TransferHandler.TransferSupport support) {
                    return false;
                }

                protected Transferable createTransferable(JComponent c) {
                    return new Transferable() {
                        @Override
                        public Object getTransferData(DataFlavor arg0)
                                throws UnsupportedFlavorException, IOException {
                            if (arg0.equals(df)) {
                                return new ByteArrayInputStream(textarea.getText().getBytes());
                            } else {
                                return textarea.getText();
                            }
                        }

                        @Override
                        public DataFlavor[] getTransferDataFlavors() {
                            return new DataFlavor[] { df, DataFlavor.stringFlavor };
                        }

                        @Override
                        public boolean isDataFlavorSupported(DataFlavor arg0) {
                            if (arg0.equals(df) || arg0.equals(DataFlavor.stringFlavor)) {
                                return true;
                            }
                            return false;
                        }
                    };
                }

                public boolean importData(TransferHandler.TransferSupport support) {
                    return false;
                }
            };
            textarea.setTransferHandler(th);
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }

        Map<Integer, String> ups = new HashMap<Integer, String>();
        Set<Integer> stuck = new HashSet<Integer>();
        Map<Integer, List<Tegeval>> ups2 = new HashMap<Integer, List<Tegeval>>();
        //int[] rr = table.getSelectedRows();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            //int cr = table.convertRowIndexToModel(r);
            //Gene gg = geneset.genelist.get(cr);
            if (gg.getSpecies() != null) {
                if (gg.genid != null && gg.genid.length() > 0) {
                    ups.put(gg.getGroupIndex(), gg.name);
                    stuck.add(gg.getGroupIndex());
                }
                if (!stuck.contains(gg.getGroupIndex())) {
                    if (!ups.containsKey(gg.getGroupIndex())
                            || !(gg.name.contains("unnamed") || gg.name.contains("hypot")))
                        ups.put(gg.getGroupIndex(), gg.name);
                }

                List<Tegeval> tlist;
                if (ups2.containsKey(gg.getGroupIndex()))
                    tlist = ups2.get(gg.getGroupIndex());
                else {
                    tlist = new ArrayList<Tegeval>();
                    ups2.put(gg.getGroupIndex(), tlist);
                }

                //textarea.append(gg.name + ":\n");
                tlist.add(gg.tegeval);
                /*textarea.append(">" + tv.cont + " " + tv.teg + " " + tv.eval + "\n");
                if (tv.dna != null) {
                   for (int i = 0; i < tv.dna.length(); i += 70) {
                      textarea.append(tv.dna.substring(i, Math.min(i + 70, tv.dna.length())) + "\n");
                   }
                }*/
            }
        }

        for (int gi : ups.keySet()) {
            String name = ups.get(gi);
            List<Tegeval> tlist = ups2.get(gi);

            textarea.append(name.replace('/', '-') + ":\n");
            for (Tegeval tv : tlist) {
                textarea.append(">" + tv.name.substring(0, tv.name.indexOf('_')) + "\n");
                for (int i = 0; i < tv.getLength(); i += 70) {
                    textarea.append(tv.getSubstring(i, Math.min(i + 70, tv.getLength())) + "\n");
                }
            }
        }

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });
    sequencemenu.getItems().add(showgroupdnaseq);
    sequencemenu.getItems().add(new SeparatorMenuItem());

    MenuItem showallseq = new MenuItem("Show all sequences");
    showallseq.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        Map<String, Sequence> contset = new HashMap<String, Sequence>();
        //int[] rr = table.getSelectedRows();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            //int cr = table.convertRowIndexToModel(r);
            //Gene gg = geneset.genelist.get(cr);
            Tegeval tv = gg.tegeval;
            String contig = tv.getContshort().getName();
            Sequence seq = tv.getProteinSequence();
            seq.setName(contig);
            serifier.mseq.put(seq.getName(), seq);
            //Sequence seq = new Sequence( contig, aa, serifier.mseq );
            serifier.addSequence(seq);
        }
        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(showallseq);

    MenuItem showseq = new MenuItem("Show sequences");
    showseq.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        //int[] rr = table.getSelectedRows();
        if (!isGeneview()) {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //GeneGroup gg = geneset.allgenegroups.get(cr);
                genegroups.add(gg);
            }
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //Gene gg = geneset.genelist.get(cr);
                genegroups.add(gg.getGeneGroup());
            }
        }
        Platform.runLater(() -> {
            Set<String> specs = null;
            if (table.getItems().size() > 1)
                specs = getSelspec(comp, geneset.specList, null);
            showSequences(comp, genegroups, false, specs);
        });
    });
    sequencemenu.getItems().add(showseq);

    MenuItem showseqwgenenames = new MenuItem("Show sequences w/genenames");
    showseqwgenenames.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        //int[] rr = table.getSelectedRows();
        if (!isGeneview()) {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //GeneGroup gg = geneset.allgenegroups.get(cr);
                genegroups.add(gg);
            }
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                //int cr = table.convertRowIndexToModel(r);
                //Gene gg = geneset.genelist.get(cr);
                genegroups.add(gg.getGeneGroup());
            }
        }
        //Set<String>   specs = null;
        //if( rr.length > 1 ) specs = getSelspec(comp, specList, null);
        showSequences(comp, genegroups, false, null, true);
    });
    sequencemenu.getItems().add(showseqwgenenames);

    MenuItem showalignseq = new MenuItem("Show aligned sequences");
    showalignseq.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        //int[] rr = table.getSelectedRows();
        if (!isGeneview()) {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg);
            }
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg.getGeneGroup());
            }
        }

        Serifier serifier = new Serifier();
        for (GeneGroup ggroup : genegroups) {
            for (Tegeval tv : ggroup.getTegevals()) {
                String selspec = tv.getContshort().getSpec();//tv.getContig();
                String spec = geneset.nameFix(selspec);
                /*if( selspec.contains("hermus") ) spec = selspec;
                else {
                   Matcher m = Pattern.compile("\\d").matcher(selspec); 
                   int firstDigitLocation = m.find() ? m.start() : 0;
                   if( firstDigitLocation == 0 ) spec = "Thermus_" + selspec;
                   else spec = "Thermus_" + selspec.substring(0,firstDigitLocation) + "_" + selspec.substring(firstDigitLocation);
                }*/

                Sequence seq = tv.getAlignedSequence();
                //System.err.println( "seqlen " + seq.length() );
                if (seq != null) {
                    seq.setName(spec);
                    //Sequence seq = new Sequence( contig, seqstr, null );
                    serifier.addSequence(seq);
                } else {
                    Sequence sb = tv.getProteinSequence();
                    sb.setName(spec);
                    //Sequence sseq = new Sequence( spec, sb, serifier.mseq );
                    serifier.addSequence(sb);
                }
            }
        }
        showAlignedSequences(comp, serifier);
    });
    sequencemenu.getItems().add(showalignseq);

    MenuItem splitseq = new MenuItem("Split/Show sequences");
    splitseq.setOnAction(actionEvent -> {
        try {
            StringBuffer sb = getSelectedASeqs(table, geneset.genelist, GeneSetHead.this, geneset.specList);
            if (geneset.currentSerify == null) {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                frame.setSize(800, 600);

                SerifyApplet sa = new SerifyApplet(geneset.zipfilesystem);
                sa.init(frame, null, geneset.user);
                geneset.currentSerify = sa;

                frame.setVisible(true);
            }
            geneset.currentSerify.addSequences("uh", new StringReader(sb.toString()), Paths.get("/"), null);
        } catch (URISyntaxException | IOException e1) {
            e1.printStackTrace();
        }

        //JTextArea textarea = new JTextArea();
        //textarea.append( sb.toString() );

        /*try {
           if (clipboardService == null)
          clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
           Action action = new CopyAction("Copy", null, "Copy data", new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
           textarea.getActionMap().put("copy", action);
           grabFocus = true;
        } catch (Exception ee) {
           ee.printStackTrace();
           System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }
                
        *
         * final DataFlavor df =
         * DataFlavor.getTextPlainUnicodeFlavor();//new
         * DataFlavor("text/plain;charset=utf-8"); final String charset
         * = df.getParameter("charset"); final Transferable transferable
         * = new Transferable() {
         * 
         * @Override public Object getTransferData(DataFlavor arg0)
         * throws UnsupportedFlavorException, IOException { String ret =
         * makeCopyString( detailTable ); return new
         * ByteArrayInputStream( ret.getBytes( charset ) ); }
         * 
         * @Override public DataFlavor[] getTransferDataFlavors() {
         * return new DataFlavor[] { df }; }
         * 
         * @Override public boolean isDataFlavorSupported(DataFlavor
         * arg0) { if( arg0.equals(df) ) { return true; } return false;
         * } };
         * 
         * TransferHandler th = new TransferHandler() { private static
         * final long serialVersionUID = 1L;
         * 
         * public int getSourceActions(JComponent c) { return
         * TransferHandler.COPY_OR_MOVE; }
         * 
         * public boolean canImport(TransferHandler.TransferSupport
         * support) { return false; }
         * 
         * protected Transferable createTransferable(JComponent c) {
         * return transferable; }
         * 
         * public boolean importData(TransferHandler.TransferSupport
         * support) { /*try { Object obj =
         * support.getTransferable().getTransferData( df ); InputStream
         * is = (InputStream)obj;
         * 
         * byte[] bb = new byte[2048]; int r = is.read(bb);
         * 
         * //importFromText( new String(bb,0,r) ); } catch
         * (UnsupportedFlavorException e) { e.printStackTrace(); } catch
         * (IOException e) { e.printStackTrace(); }* return false; } };
         * textarea.setTransferHandler( th );
         *
        textarea.setDragEnabled(true);
                
        JScrollPane scrollpane = new JScrollPane(textarea);
                
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);*/
    });
    sequencemenu.getItems().add(splitseq);

    MenuItem showdnaseq = new MenuItem("Show DNA sequences");
    showdnaseq.setOnAction(actionEvent -> {
        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        int rr = 0;
        if (!isGeneview()) {
            ObservableList<GeneGroup> lgg = table.getSelectionModel().getSelectedItems();
            genegroups.addAll(lgg);
            rr = lgg.size();
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg.getGeneGroup());
                rr++;
            }
        }
        Set<String> specs = null;
        if (rr > 1)
            specs = getSelspec(comp, geneset.specList, null);
        showSequences(comp, genegroups, true, specs);

        /*StringBuilder sb = getSelectedSeqs( table, genelist );
                
        if( currentSerify == null ) {
           JFrame frame = new JFrame();
           frame.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
           frame.setSize(800, 600);
                   
           SerifyApplet sa = new SerifyApplet();
           sa.init( frame );
                   
           try {
          sa.addSequences("uh", new StringReader( sb.toString() ), "/");
           } catch (URISyntaxException | IOException e1) {
          e1.printStackTrace();
           }
                   
           frame.setVisible( true );
        }
                
        JTextArea textarea = new JTextArea();
        JScrollPane scrollpane = new JScrollPane(textarea);
                
        try {
           if (clipboardService == null)
          clipboardService = (ClipboardService) ServiceManager.lookup("javax.jnlp.ClipboardService");
           Action action = new CopyAction("Copy", null, "Copy data", new Integer(KeyEvent.VK_CONTROL + KeyEvent.VK_C));
           textarea.getActionMap().put("copy", action);
           grabFocus = true;
        } catch (Exception ee) {
           ee.printStackTrace();
           System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        }
                
        textarea.setDragEnabled(true);
        textarea.append( sb.toString() );
                
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);*/
    });
    sequencemenu.getItems().add(showdnaseq);

    MenuItem expalldna = new MenuItem("Export all DNA sequences");
    expalldna.setOnAction(actionEvent -> {
        JFileChooser jfc = new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        try {
            Map<Integer, FileWriter> lfw = new HashMap<Integer, FileWriter>();
            if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File f = jfc.getSelectedFile();
                for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                    FileWriter fw = null;
                    if (lfw.containsKey(gg.getGroupIndex())) {
                        fw = lfw.get(gg.getGroupIndex());
                    } else {
                        fw = new FileWriter(new File(f, "group_" + gg.getGroupIndex() + ".fasta"));
                        lfw.put(gg.getGroupIndex(), fw);
                    }

                    Tegeval tv = gg.tegeval;
                    fw.append(">" + tv.name + " " + tv.teg + " " + tv.eval + "\n");
                    for (int i = 0; i < tv.getLength(); i += 70) {
                        fw.append(tv.getSubstring(i, Math.min(i + 70, tv.getLength())) + "\n");
                    }
                }
            }
            for (int gi : lfw.keySet()) {
                lfw.get(gi).close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    sequencemenu.getItems().add(expalldna);

    MenuItem exprelcont = new MenuItem("Export relevant contigs");
    exprelcont.setOnAction(actionEvent -> {
        JFileChooser jfc = new JFileChooser();

        try {
            Map<Integer, FileWriter> lfw = new HashMap<Integer, FileWriter>();
            if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File f = jfc.getSelectedFile();

                Set<Sequence> contset = new HashSet<Sequence>();
                for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                    Tegeval tv = gg.tegeval;
                    contset.add(tv.getContshort());
                }

                FileWriter fw = new FileWriter(f);
                for (Sequence contig : contset) {
                    fw.append(">" + contig + "\n");
                    if (geneset.contigmap.containsKey(contig)) {
                        StringBuilder dna = geneset.contigmap.get(contig).getStringBuilder();
                        for (int i = 0; i < dna.length(); i += 70) {
                            fw.append(dna.substring(i, Math.min(i + 70, dna.length())) + "\n");
                        }
                    }
                }
                fw.close();
            }
            for (int gi : lfw.keySet()) {
                lfw.get(gi).close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    sequencemenu.getItems().add(exprelcont);
    sequencemenu.getItems().add(new SeparatorMenuItem());

    MenuItem viewselrange = new MenuItem("View selected range");
    viewselrange.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        Set<Sequence> contset = new HashSet<Sequence>();
        Set<Tegeval> tvset = new HashSet<>();
        if (isGeneview()) {
            for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                Tegeval tv = gg.tegeval;
                tvset.add(tv);
                //serifier.addAnnotation( tv );
                contset.add(tv.getContshort());
            }
        } else {
            for (GeneGroup gg : getGeneGroupTable().getSelectionModel().getSelectedItems()) {
                for (Tegeval tv : gg.getTegevals()) {
                    tv.color = Color.red;
                    tvset.add(tv);
                    Sequence contig = tv.getContshort();
                    contset.add(contig);
                    //serifier.addAnnotation( tv );
                }
            }
        }
        /*Sequence seq;
        Sequence contig = tv.getContshort();
        /*if (contset.containsKey(contig)) {
          seq = contset.get(contig);
        } else {
          if( contigmap.containsKey(contig) ) {
             StringBuilder dna = contigmap.get(contig).getStringBuilder();
             seq = new Sequence(contig.getName(), dna, serifier.mseq);
          } else
             seq = new Sequence(contig.getName(), serifier.mseq);
          contset.put(contig, seq);
        }
                
        Annotation a = new Annotation(contig, contig.getName(), Color.green, serifier.mann);
        a.setStart(tv.start);
        a.setStop(tv.stop);
        a.setOri(tv.ori);
        a.setGroup(gg.name);
        a.setType("gene");*/
        // seq.addAnnotation( new Annotation( seq, ) );

        for (Sequence contig : contset) {
            int start = Integer.MAX_VALUE;
            int stop = Integer.MIN_VALUE;
            for (Tegeval tv : tvset) {
                if (contig == tv.seq) {
                    start = Math.min(start, tv.start);
                    stop = Math.max(stop, tv.stop);
                }
            }

            int rstart = 0;
            int rstop = contig.length();
            if (contig.annset != null)
                for (Annotation tv : contig.annset) {
                    if (contig == tv.seq) {
                        if (tv.stop < start && tv.stop > rstart) {
                            rstart = tv.stop;
                        }
                        if (tv.start > stop && tv.start < rstop) {
                            rstop = tv.start;
                        }
                    }
                }

            start = rstart;
            stop = rstop;

            Sequence newseq = new Sequence(contig.getName(),
                    new StringBuilder(contig.getSubstring(start, stop, 1)), serifier.mseq);
            /*if( contig.isReverse() ) {
               newseq.reverse();
               newseq.complement();
            }*/

            serifier.addSequence(newseq);
            for (Tegeval tv : tvset) {
                Annotation newann = new Annotation(newseq, tv.start - start, tv.stop - start, tv.ori, tv.name);
                if (contig == tv.seq) {
                    newseq.addAnnotation(newann);
                }
                serifier.addAnnotation(newann);
            }
            /*for( Annotation ann : contig.getAnnotations() ) {
               serifier.addAnnotation( ann );
            }*/
            /*if (seq.getAnnotations() != null)
               Collections.sort(seq.getAnnotations());*/
        }
        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(viewselrange);

    MenuItem viewwhole = new MenuItem("View whole contigs for selection");
    viewwhole.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        //Map<Sequence, Sequence> contset = new HashMap<Sequence, Sequence>();
        /*int[] rr = table.getSelectedRows();
        for (int r : rr) {
           int cr = table.convertRowIndexToModel(r);
           Gene gg = geneset.genelist.get(cr);
           if (gg.species != null) {
          for (String sp : gg.species.keySet()) {
             Teginfo stv = gg.species.get(sp);
             for (Tegeval tv : stv.tset) {
                Sequence seq;
                Sequence contig = tv.getContshort();
                if (contset.containsKey(contig)) {
                   seq = contset.get(contig);
                } else {
                   if( GeneSet.contigmap.containsKey(contig) ) {
                      //StringBuilder dna = GeneSet.contigmap.get(contig).seq;
                      StringBuilder dna = contig.getSequence().getStringBuilder();
                      seq = new Sequence(contig.getName(), dna, serifier.mseq);
                   } else {
                      seq = new Sequence(contig.getName(), serifier.mseq);
                   }
                
                   contset.put(contig, seq);
                }
                
                /*
                 * Annotation a = jf.new Annotation( seq,
                 * contig, Color.red ); a.setStart( tv.start );
                 * a.setStop( tv.stop ); a.setOri( tv.ori );
                 * a.setGroup( gg.name ); a.setType( "gene" );
                 * jf.addAnnotation( a );
                 *
                // seq.addAnnotation( new Annotation( seq, ) );
             }
          }
           }
        }*/

        Set<Sequence> contigs = new HashSet<Sequence>();
        if (isGeneview()) {
            for (Gene gg : getGeneTable().getSelectionModel().getSelectedItems()) {
                Tegeval tv = gg.tegeval;
                tv.color = Color.red;
                Sequence contig = tv.getContshort();
                //contig.offset = -tv.start;
                contigs.add(contig);
            }

            /*Annotation a = new Annotation(contig, contig.getName(), Color.red, serifier.mann);
            a.setStart(tv.start);
            a.setStop(tv.stop);
            a.setOri(tv.ori);
            a.setGroup(g.name);
            a.setType("gene");*/
            //serifier.addAnnotation( tv );
        } else {
            for (GeneGroup gg : getGeneGroupTable().getSelectionModel().getSelectedItems()) {
                for (Tegeval tv : gg.getTegevals()) {
                    tv.color = Color.red;
                    Sequence contig = tv.getContshort();
                    //contig.offset = -tv.start;
                    contigs.add(contig);

                    /*Annotation a = new Annotation(contig, contig.getName(), Color.red, serifier.mann);
                    a.setStart(tv.start);
                    a.setStop(tv.stop);
                    a.setOri(tv.ori);
                    a.setGroup(gg.getCommonName());
                    a.setType("gene");*/
                    //serifier.addAnnotation( tv );
                }
            }
        }
        //Gene gg = geneset.genelist.get(cr);
        //for (Gene g : geneset.genelist) {
        //if (g.species != null) {
        //for (String sp : g.species.keySet()) {

        for (Sequence contig : contigs) {
            for (Annotation ann : contig.getAnnotations()) {
                serifier.addAnnotation(ann);
            }

            serifier.addSequence(contig);
            serifier.mseq.put(contig.getName(), contig);
            //if(contig.getAnnotations() != null)
            //   Collections.sort(contig.getAnnotations());
        }
        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(viewwhole);
    sequencemenu.getItems().add(new SeparatorMenuItem());

    MenuItem viewspecseq = new MenuItem("View species sequence");
    viewspecseq.setOnAction(actionEvent -> {
        Set<String> selspec = getSelspec(GeneSetHead.this, geneset.specList);

        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);

        for (String spec : selspec) {
            List<Sequence> contigs = geneset.speccontigMap.get(spec);

            for (Sequence contig : contigs) {
                List<Annotation> lann = contig.getAnnotations();
                if (lann != null)
                    for (Annotation ann : lann) {
                        serifier.addAnnotation(ann);
                    }

                serifier.addSequence(contig);
                serifier.mseq.put(contig.getName(), contig);
            }
        }

        jf.updateView();

        frame.setVisible(true);
    });
    sequencemenu.getItems().add(viewspecseq);

    Menu windowmenu = new Menu("Tools");
    MenuItem seqviewer = new MenuItem("Sequence viewer");
    seqviewer.setOnAction(actionEvent -> {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Serifier serifier = new Serifier();
        JavaFasta jf = new JavaFasta((comp instanceof JApplet) ? (JApplet) comp : null, serifier, geneset.cs);
        jf.initGui(frame);
        jf.updateView();

        frame.setVisible(true);
    });
    windowmenu.getItems().add(seqviewer);
    windowmenu.getItems().add(new SeparatorMenuItem());
    MenuItem genesorter = new MenuItem("Gene sorter");
    genesorter.setOnAction(actionEvent -> {
        try {
            //if( gb.isSelected() ) new GeneSorter().mynd( GeneSetHead.this, genelist, table, null, contigmap );
            //else 
            new GeneSorter().groupMynd(GeneSetHead.this, geneset.allgenegroups, geneset.specList,
                    geneset.genelist, table, geneset.contigmap, geneset.specset);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    windowmenu.getItems().add(genesorter);
    MenuItem specorderaction = new MenuItem("Order species list");
    specorderaction.setOnAction(actionEvent -> {
        TreeUtil tu = new TreeUtil();
        /*corrInd.clear();
        for( String spec : specList ) {
           corrInd.add( nameFix( spec ) );
        }*/

        Serifier serifier = getConcatenatedSequences(false, false);

        Map<String, Integer> blosumap = JavaFasta.getBlosumMap();
        double[] dmat = new double[serifier.lseq.size() * serifier.lseq.size()];
        Sequence.distanceMatrixNumeric(serifier.lseq, dmat, null, false, false, null, blosumap);

        List<String> ret = new ArrayList<String>();
        for (Sequence seqname : serifier.lseq) {
            ret.add(seqname.getName()); //.replace(' ', '_') );
        }
        //List<String>   corrInd = currentjavafasta.getNames();

        //Sequence.distanceMatrixNumeric(serifier.lseq, dmat, idxs, bootstrap, cantor, ent, blosum);
        Node n = tu.neighborJoin(dmat, ret, null, false, false);

        Comparator<Node> comp2 = (o1, o2) -> {
            int c1 = o1.countLeaves();
            int c2 = o2.countLeaves();

            if (c1 > c2)
                return 1;
            else if (c1 == c2)
                return 0;

            return -1;
        };
        tu.arrange(n, comp2);
        //corrInd.clear();
        List<String> ordInd = n.traverse();

        for (String spec : ordInd) {
            System.err.println(spec);
        }

        for (String oldspec : geneset.specList) {
            if (!ordInd.contains(oldspec)) {
                ordInd.add(oldspec);
            }
        }
        geneset.specList = ordInd;

        //TableModel model = table.getModel();
        //table.setModel( nullmodel );
        //table.setModel( model );

        //table.tableChanged( new TableModelEvent( table.getModel() ) );
        //table.getColumnModel().
        System.err.println(geneset.specList.size());
    });
    MenuItem matrixaction = new MenuItem("Relation matrix");
    matrixaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            JComboBox<String> descombo = new JComboBox<String>(
                    geneset.deset.toArray(new String[geneset.deset.size()]));
            JCheckBox anicheck = new JCheckBox("ANImatrix");
            JCheckBox plasmidcheck = new JCheckBox("Skip plasmids");
            descombo.insertItemAt("", 0);
            descombo.setSelectedIndex(0);
            JOptionPane.showMessageDialog(GeneSetHead.this, new Object[] { descombo, anicheck, plasmidcheck });
            String val = descombo.getSelectedItem().toString();

            Collection<GeneGroup> ss = new HashSet<>();
            /*int[] rr = table.getSelectedRows();
            for( int r : rr ) {
               ss.add( geneset.allgenegroups.get( table.convertRowIndexToModel(r) ) );
            }*/
            ss.addAll(table.getSelectionModel().getSelectedItems());
            if (ss.isEmpty())
                ss = geneset.allgenegroups;

            Set<String> species = getSelspec(GeneSetHead.this, geneset.specList);
            bimg = anicheck.isSelected()
                    ? geneset.animatrix(species, geneset.clusterMap, val, ss, plasmidcheck.isSelected())
                    : geneset.bmatrix(species, geneset.clusterMap, val);

            JFrame f = new JFrame("Relation matrix");
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setSize(500, 500);

            /*
             * { public void paintComponent( Graphics g ) {
             * super.paintComponent(g); g.drawImage(bimg, 0, 0, this); } };
             */

            try {
                final DataFlavor df = new DataFlavor("text/plain;charset=utf-8");
                final Transferable transferable = new Transferable() {
                    @Override
                    public Object getTransferData(DataFlavor arg0)
                            throws UnsupportedFlavorException, IOException {
                        StringBuilder ret = new StringBuilder();

                        int i = 0;
                        for (String spc : geneset.specList) {
                            if (++i == geneset.specList.size())
                                ret.append(spc + "\n");
                            else
                                ret.append(spc + "\t");
                        }

                        int where = 0;
                        for (String spc1 : geneset.specList) {
                            int wherex = 0;
                            for (String spc2 : geneset.specList) {
                                int spc1tot = 0;
                                int spc2tot = 0;
                                int totot = 0;

                                int spc1totwocore = 0;
                                int spc2totwocore = 0;
                                int tototwocore = 0;
                                for (Set<String> set : geneset.clusterMap.keySet()) {
                                    Set<Map<String, Set<String>>> erm = geneset.clusterMap.get(set);
                                    if (set.contains(spc1)) {
                                        if (set.size() < geneset.specList.size()) {
                                            spc1totwocore += erm.size();
                                            for (Map<String, Set<String>> sm : erm) {
                                                Set<String> hset = sm.get(spc1);
                                                tototwocore += hset.size();
                                            }

                                            if (set.contains(spc2)) {
                                                spc2totwocore += erm.size();
                                            }

                                            if (spc2totwocore > spc1totwocore)
                                                System.err.println(
                                                        "okoko " + spc1totwocore + " " + spc2totwocore);
                                        }

                                        spc1tot += erm.size();
                                        for (Map<String, Set<String>> sm : erm) {
                                            Set<String> hset = sm.get(spc1);
                                            totot += hset.size();
                                        }

                                        if (set.contains(spc2)) {
                                            spc2tot += erm.size();
                                        }
                                    }
                                }

                                if (where == wherex) {
                                    if (where == geneset.specList.size() - 1)
                                        ret.append(0 + "\n");
                                    else
                                        ret.append(0 + "\t");
                                } else {
                                    double hlut = (double) spc2totwocore / (double) spc1totwocore;
                                    double sval = hlut; // 1.0/( 1.1-hlut );
                                    double val = Math.pow(50.0, sval - 0.3) - 1.0;
                                    double dval = Math.round(100.0 * (val)) / 100.0;

                                    if (wherex == geneset.specList.size() - 1)
                                        ret.append(dval + "\n");
                                    else
                                        ret.append(dval + "\t");
                                }
                                wherex++;
                            }
                            where++;
                        }

                        return new ByteArrayInputStream(ret.toString().getBytes());
                    }

                    @Override
                    public DataFlavor[] getTransferDataFlavors() {
                        return new DataFlavor[] { df };
                    }

                    @Override
                    public boolean isDataFlavorSupported(DataFlavor arg0) {
                        if (arg0.equals(df)) {
                            return true;
                        }
                        return false;
                    }
                };
                final TransferComponent comp2 = new TransferComponent(bimg, transferable);

                TransferHandler th = new TransferHandler() {
                    private static final long serialVersionUID = 1L;

                    public int getSourceActions(JComponent c) {
                        return TransferHandler.COPY_OR_MOVE;
                    }

                    public boolean canImport(TransferSupport support) {
                        return false;
                    }

                    protected Transferable createTransferable(JComponent c) {
                        return transferable;
                    }

                    public boolean importData(TransferSupport support) {
                        return true;
                    }
                };
                comp2.setTransferHandler(th);

                comp2.setEnabled(true);
                JScrollPane fsc = new JScrollPane(comp2);
                comp2.setPreferredSize(new Dimension(bimg.getWidth(), bimg.getHeight()));

                JPopupMenu popup = new JPopupMenu();
                popup.add(new AbstractAction("Save image") {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        FileSaveService fss = null;
                        FileContents fileContents = null;

                        try {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            OutputStreamWriter osw = new OutputStreamWriter(baos);
                            ImageIO.write(bimg, "png", baos);
                            baos.close();

                            try {
                                fss = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
                            } catch (UnavailableServiceException e1) {
                                fss = null;
                            }

                            if (fss != null) {
                                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                                fileContents = fss.saveFileDialog(null, null, bais, "export.png");
                                bais.close();
                                OutputStream os = fileContents.getOutputStream(true);
                                os.write(baos.toByteArray());
                                os.close();
                            } else {
                                JFileChooser jfc = new JFileChooser();
                                if (jfc.showSaveDialog(GeneSetHead.this) == JFileChooser.APPROVE_OPTION) {
                                    File f = jfc.getSelectedFile();
                                    FileOutputStream fos = new FileOutputStream(f);
                                    fos.write(baos.toByteArray());
                                    fos.close();

                                    Desktop.getDesktop().browse(f.toURI());
                                }
                            }
                        } catch (IOException e2) {
                            e2.printStackTrace();
                        }
                    }
                });
                comp2.setComponentPopupMenu(popup);

                f.add(fsc);
                f.setVisible(true);
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }
        });
    });
    MenuItem tniaction = new MenuItem("TNI/ANI");
    tniaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            Set<String> species = getSelspec(GeneSetHead.this, geneset.specList);
            String makeblastdb = "makeblastdb";
            String OS = System.getProperty("os.name").toLowerCase();
            if (OS.indexOf("mac") != -1)
                makeblastdb = "/usr/local/bin/makeblastdb";
            for (String spec : species) {
                List<Sequence> lseq = geneset.speccontigMap.get(spec);
                ProcessBuilder pb = new ProcessBuilder(makeblastdb, "-dbtype", "nucl", "-title", spec, "-out",
                        spec);
                File dir = new File(System.getProperty("user.home"));

                /*try {
                    FileWriter w = new FileWriter( new File(dir, spec+".fna") );
                    for( Sequence seq : lseq ) {
                seq.writeSequence(w);
                    }
                    w.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }*/

                pb.directory(dir);
                try {
                    Process p = pb.start();
                    Writer fw = new OutputStreamWriter(p.getOutputStream());
                    for (Sequence seq : lseq) {
                        seq.writeSequence(fw);
                    }
                    fw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            int y = 0;
            double[] matrix = new double[species.size() * species.size()];
            for (String dbspec : species) {
                int x = 0;
                for (String spec : species) {
                    //if( !spec.equals(dbspec) ) {
                    final List<Sequence> lseq = geneset.speccontigMap.get(spec);
                    String blastn = "blastn";
                    if (OS.indexOf("mac") != -1)
                        blastn = "/usr/local/bin/blastn";
                    ProcessBuilder pb = new ProcessBuilder(blastn, "-db", dbspec, "-num_threads",
                            Integer.toString(Runtime.getRuntime().availableProcessors()), "-num_alignments",
                            "1", "-num_descriptions", "1"); //,"-max_hsps","1");
                    File dir = new File(System.getProperty("user.home"));
                    pb.directory(dir);
                    try {
                        Process p = pb.start();
                        final BufferedWriter fw = new BufferedWriter(
                                new OutputStreamWriter(p.getOutputStream()));
                        Thread t = new Thread() {
                            public void run() {
                                try {
                                    for (Sequence seq : lseq) {
                                        seq.writeSplitSequence(fw);
                                        //seq.writeSequence(fw);
                                    }
                                    fw.close();
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        };
                        t.start();
                        //Path path = Paths.get("/Users/sigmar/"+spec+"_"+dbspec+".blastout");
                        //Files.copy(p.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

                        int tnum = 0;
                        int tdenum = 0;
                        double avg = 0.0;
                        int count = 0;

                        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        String line = br.readLine();
                        while (line != null) {
                            if (line.startsWith(" Identities")) {
                                int i = line.indexOf('(');
                                String sub = line.substring(14, i - 1);
                                String[] split = sub.split("/");
                                int num = Integer.parseInt(split[0]);
                                int denum = Integer.parseInt(split[1]);

                                avg += (double) num / (double) denum;

                                tnum += num;
                                tdenum += denum;
                                count++;
                            }
                            line = br.readLine();
                        }
                        br.close();

                        if (count > 0)
                            avg /= count;
                        double val = (double) tnum / (double) tdenum;
                        matrix[y * species.size() + x] = avg;//val;
                        System.err.println(spec + " on " + dbspec + " " + val);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    //}
                    x++;
                }
                y++;
            }

            geneset.corrInd.clear();
            for (String spec : species) {
                geneset.corrInd.add(geneset.nameFix(spec));
            }

            final BufferedImage bi = geneset.showRelation(geneset.corrInd, matrix, false);
            JFrame f = new JFrame("TNI matrix");
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setSize(500, 500);

            JComponent comp2 = new JComponent() {
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.drawImage(bi, 0, 0, bi.getWidth(), bi.getHeight(), 0, 0, bi.getWidth(), bi.getHeight(),
                            this);
                }
            };
            Dimension dim = new Dimension(bi.getWidth(), bi.getHeight());
            comp2.setPreferredSize(dim);
            comp2.setSize(dim);
            JScrollPane scroll = new JScrollPane(comp2);
            f.add(scroll);

            f.setVisible(true);
        });
    });
    MenuItem anitreeaction = new MenuItem("ANI tree");
    anitreeaction.setOnAction(actionEvent -> {
        Set<String> species = getSelspec(GeneSetHead.this, geneset.specList);
        List<String> speclist = new ArrayList<String>(species);

        Collection<GeneGroup> allgg = new HashSet<GeneGroup>();
        allgg.addAll(table.getSelectionModel().getSelectedItems());
        if (allgg.isEmpty())
            allgg = geneset.allgenegroups;
        Map<String, Integer> blosumap = JavaFasta.getBlosumMap();

        double[] corrarr = new double[speclist.size() * speclist.size()];
        int where = 0;
        for (String spec1 : speclist) {
            int wherex = 0;

            String spc1 = geneset.nameFix(spec1);

            //String spc1 = nameFix( spec1 );
            for (String spec2 : speclist) {
                if (where != wherex) {
                    int totalscore = 0;
                    int totaltscore = 1;
                    for (GeneGroup gg : allgg) {
                        if ( /*gg.getSpecies().size() > 40 &&*/ gg.getSpecies().contains(spec1)
                                && gg.getSpecies().contains(spec2)) {
                            Teginfo ti1 = gg.species.get(spec1);
                            Teginfo ti2 = gg.species.get(spec2);
                            //if( ti1.tset.size() == 1 && ti2.tset.size() == 1 ) {
                            //double bval = 0.0;

                            int score = 0;
                            int tscore = 1;
                            for (Tegeval tv1 : ti1.tset) {
                                for (Tegeval tv2 : ti2.tset) {
                                    Sequence seq1 = tv1.getAlignedSequence();
                                    Sequence seq2 = tv2.getAlignedSequence();
                                    if (seq1 != null && seq2 != null) {
                                        int mest = 0;
                                        int tmest = 0;

                                        int startcheck = 0;
                                        int start = -1;
                                        int stopcheck = 0;
                                        int stop = -1;
                                        for (int i = 0; i < seq1.length(); i++) {
                                            if (seq1.getCharAt(i) != '-') {
                                                startcheck |= 1;
                                            }
                                            if (seq2.getCharAt(i) != '-') {
                                                startcheck |= 2;
                                            }

                                            if (start == -1 && startcheck == 3) {
                                                start = i;
                                                break;
                                            }
                                        }

                                        for (int i = seq1.length() - 1; i >= 0; i--) {
                                            if (seq1.getCharAt(i) != '-') {
                                                stopcheck |= 1;
                                            }
                                            if (seq2.getCharAt(i) != '-') {
                                                stopcheck |= 2;
                                            }

                                            if (stop == -1 && stopcheck == 3) {
                                                stop = i + 1;
                                                break;
                                            }
                                        }
                                        //count += stop-start;

                                        for (int i = start; i < stop; i++) {
                                            char lc = seq1.getCharAt(i);
                                            char c = Character.toUpperCase(lc);
                                            //if( )
                                            String comb = c + "" + c;
                                            if (blosumap.containsKey(comb))
                                                tmest += blosumap.get(comb);
                                        }

                                        for (int i = start; i < stop; i++) {
                                            char lc = seq1.getCharAt(i);
                                            char c = Character.toUpperCase(lc);
                                            char lc2 = seq2.getCharAt(i);
                                            char c2 = Character.toUpperCase(lc2);

                                            String comb = c + "" + c2;
                                            if (blosumap.containsKey(comb))
                                                mest += blosumap.get(comb);
                                        }

                                        double tani = (double) mest / (double) tmest;
                                        if (tani > (double) score / (double) tscore) {
                                            score = mest;
                                            tscore = tmest;
                                        }
                                        //ret = (double)score/(double)tscore; //int cval = tscore == 0 ? 0 : Math.min( 192, 512-score*512/tscore );
                                        //return ret;
                                    }
                                    //if( where == 0 ) d1.add( gg.getCommonName() );
                                    //else d2.add( gg.getCommonName() );
                                }
                            }
                            totalscore += score;
                            totaltscore += tscore;

                            /*if( bval > 0 ) {
                               ani += bval;
                               count++;
                            }*/
                            //}
                        }
                    }
                    double ani = (double) (totaltscore - totalscore) / (double) totaltscore;
                    corrarr[where * speclist.size() + wherex] = ani;
                }
                wherex++;
            }
            where++;
        }
        TreeUtil tu = new TreeUtil();
        geneset.corrInd.clear();
        for (String spec : speclist) {
            geneset.corrInd.add(geneset.nameFix(spec));
        }
        Node n = tu.neighborJoin(corrarr, geneset.corrInd, null, false, false);
        System.err.println(n);
    });
    windowmenu.getItems().add(specorderaction);
    windowmenu.getItems().add(matrixaction);
    windowmenu.getItems().add(tniaction);
    windowmenu.getItems().add(anitreeaction);

    MenuItem neighbourhood = new MenuItem("Neighbourhood");
    neighbourhood.setOnAction(actionEvent -> {
        try {
            Set<GeneGroup> genset = new HashSet<>();
            if (!isGeneview()) {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    genset.add(gg);
                }
            } else {
                for (Gene gene : gtable.getSelectionModel().getSelectedItems()) {
                    genset.add(gene.getGeneGroup());
                }
            }
            new Neighbour(genset).neighbourMynd(GeneSetHead.this, comp, geneset.genelist, geneset.contigmap);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    windowmenu.getItems().add(neighbourhood);

    MenuItem synteny = new MenuItem("Synteny");
    synteny.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            //Set<String> species = speciesFromCluster( clusterMap );
            new Synteni().syntenyMynd(GeneSetHead.this, comp, geneset.genelist);
        });
    });
    windowmenu.getItems().add(synteny);
    MenuItem compareplotaction = new MenuItem("Gene atlas");
    compareplotaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            try {
                new GeneCompare().comparePlot(GeneSetHead.this, comp, geneset.genelist, geneset.clusterMap,
                        8192, 8192);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        });

        /*gatest("MAT4726");
                
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
        frame.setSize(800, 600);
                
        final JComponent c = new JComponent() {
           public void paintComponent( Graphics g ) {
          g.drawImage(bimg, 0, 0, frame);
           }
        };
        c.setPreferredSize( new Dimension(bimg.getWidth(), bimg.getHeight()) );
        JScrollPane   scrollpane = new JScrollPane( c );
        frame.add( scrollpane );
        frame.setVisible( true );*/
    });
    windowmenu.getItems().add(compareplotaction);

    MenuItem syntenygradientaction = new MenuItem("Synteny gradient");
    syntenygradientaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            Set<String> presel = new HashSet<>();
            if (isGeneview()) {
                for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                    presel.addAll(g.getGeneGroup().getSpecies());
                }
            } else {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    presel.addAll(gg.getSpecies());
                }
            }
            new SyntGrad().syntGrad(GeneSetHead.this, 4096, 4096, presel);
        });
    });
    windowmenu.getItems().add(syntenygradientaction);

    MenuItem genexyplotaction = new MenuItem("Gene XY plot");
    genexyplotaction.setOnAction(actionEvent -> SwingUtilities.invokeLater(
            () -> new XYPlot().xyPlot(GeneSetHead.this, comp, geneset.genelist, geneset.clusterMap)));
    windowmenu.getItems().add(genexyplotaction);

    MenuItem refalignaction = new MenuItem("Reference align");
    refalignaction.setOnAction(actionEvent -> {
        SwingUtilities.invokeLater(() -> {
            final TableView<Gene> table12 = getGeneTable();
            final Collection<String> specset = geneset.getSpecies(); //speciesFromCluster( clusterMap );
            final List<String> species = new ArrayList<>(specset);

            TableModel model = new TableModel() {
                @Override
                public int getRowCount() {
                    return species.size();
                }

                @Override
                public int getColumnCount() {
                    return 1;
                }

                @Override
                public String getColumnName(int columnIndex) {
                    return null;
                }

                @Override
                public Class<?> getColumnClass(int columnIndex) {
                    return String.class;
                }

                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return false;
                }

                @Override
                public Object getValueAt(int rowIndex, int columnIndex) {
                    return geneset.nameFix(species.get(rowIndex));
                }

                @Override
                public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
                }

                @Override
                public void addTableModelListener(TableModelListener l) {
                }

                @Override
                public void removeTableModelListener(TableModelListener l) {
                }
            };
            JTable table1 = new JTable(model);
            JTable table2 = new JTable(model);

            table1.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table2.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

            JScrollPane scroll1 = new JScrollPane(table1);
            JScrollPane scroll2 = new JScrollPane(table2);

            FlowLayout flowlayout = new FlowLayout();
            JComponent c = new JComponent() {
            };
            c.setLayout(flowlayout);

            c.add(scroll1);
            c.add(scroll2);

            JOptionPane.showMessageDialog(comp, c);

            int r = table1.getSelectedRow();
            int i = table1.convertRowIndexToModel(r);
            String spec = i == -1 ? null : species.get(i);
            List<Sequence> lcont = geneset.speccontigMap.get(spec);

            r = table2.getSelectedRow();
            i = table2.convertRowIndexToModel(r);
            String refspec = i == -1 ? null : species.get(i);
            List<Sequence> lrefcont = geneset.speccontigMap.get(spec);

            /*ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Writer fw = new OutputStreamWriter( baos );
            try {
            List<Sequence> lcont = geneset.speccontigMap.get(spec);
            for( Sequence seq : lcont ) {
                seq.writeSequence(fw);
            }
            fw.close();
            } catch (IOException e1) {
            e1.printStackTrace();
            }
                    
            String comp = spec;
            byte[] bb = baos.toByteArray();*/

            FlxReader flx = new FlxReader();

            Map<String, String> env = new HashMap<String, String>();
            env.put("create", "true");
            //String uristr = "jar:" + geneset.zippath.toUri();
            //URI geneset.zipuri = URI.create( uristr /*.replace("file://", "file:")*/ );

            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                    Path subf = root.resolve(spec + ".grp");
                    if (Files.exists(subf)) {
                        BufferedReader br = Files.newBufferedReader(subf);
                        Map<String, Map<String, String>> mm = flx.loadContigGraph(br);
                        br.close();

                        String home = System.getProperty("user.home") + "/";
                        StringBuilder sb = comp != null
                                ? flx.referenceAssembly(home, spec, refspec, lrefcont, lcont)
                                : null;
                        Sequence cseq = new Sequence(spec + "_chromosome", null);
                        if (sb != null && sb.length() > 0) {
                            br = new BufferedReader(new StringReader(sb.toString()));
                        } else {
                            Path sca = root.resolve(spec + ".csc");
                            if (!Files.exists(sca)) {
                                sca = root.resolve(spec + ".sca");
                            }
                            br = Files.newBufferedReader(sca);
                        }
                        //br = new BufferedReader( fr );

                        flx.connectContigs(br, cseq, false, new FileWriter(home + spec + "_new.fna"), spec);
                        br.close();
                    }

                    break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    geneset.zipfilesystem.close();
                } catch (IOException ie) {
                    ie.printStackTrace();
                }
                ;
            }
        });

        //flx.start( f.getParentFile().getAbsolutePath()+"/", f.getName(), false, fw, comp, bb);
    });
    windowmenu.getItems().add(refalignaction);

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

    MenuItem runantismash = new MenuItem("Run antismash");
    runantismash.setOnAction(actionEvent -> SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                Serifier ser = new Serifier();
                Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

                JTextField host = new JTextField("localhost");
                JOptionPane.showMessageDialog(null, host);

                String username = System.getProperty("user.name");
                String hostname = host.getText();

                /*Path[] pt = null;
                JFileChooser fc = new JFileChooser();
                fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
                if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
                   pt = new Path[3];
                   pt[2] = fc.getSelectedFile().toPath();
                }*/

                List<Object> commands = new ArrayList<Object>();
                //commands.add(genexyplotaction)

                for (String spec : selspec) {
                    Path pp = Paths.get(userhome);
                    Path p = pp.resolve(spec + ".gbk");
                    //BufferedWriter fw = Files.newBufferedWriter( p );
                    List<Sequence> clist = geneset.speccontigMap.get(spec);

                    Map<String, List<Annotation>> mapan = new HashMap<String, List<Annotation>>();
                    Serifier serifier = new Serifier();
                    for (Sequence c : clist) {
                        serifier.addSequence(c);
                        serifier.mseq.put(c.getName(), c);

                        List<Annotation> lann = new ArrayList<Annotation>();
                        if (c.getAnnotations() != null)
                            for (Annotation ann : c.getAnnotations()) {
                                Tegeval tv = (Tegeval) ann;

                                Gene g = tv.getGene();
                                GeneGroup gg = g.getGeneGroup();
                                String name = g.getName();
                                if (gg != null && name.contains(spec)) {
                                    name = gg.getName();
                                }
                                Annotation anno = new Annotation(c, tv.start, tv.stop, tv.ori, name);
                                anno.id = tv.getGene().getId();
                                anno.type = "CDS";

                                String cazy = gg != null ? gg.getCommonCazy(geneset.cazymap) : null;
                                if (cazy != null)
                                    anno.addDbRef("CAZY:" + cazy);
                                lann.add(anno);
                            }
                        mapan.put(c.getName(), lann);
                    }
                    Sequences s = new Sequences(null, spec, "nucl", null, clist.size());
                    //serifier.addSequences(seqs);
                    serifier.writeGenebank(p, false, true, s, mapan);

                    //fw.close();

                    String apath = p.toAbsolutePath().toString();
                    if (hostname.equals("localhost")) {
                        String[] cmds = { "run_antismash", apath };
                        //commands.add( pt );
                        commands.add(Arrays.asList(cmds));
                    } else {
                        String aname = p.getFileName().toString();
                        String adir = aname.substring(0, aname.length() - 4);
                        String cyghome = NativeRun.cygPath(userhome);
                        String[] cmds = { "scp", apath, hostname + ":~", ";", "ssh", hostname, "run_antismash",
                                aname, ";", "scp", "-r", hostname + ":~/" + adir, cyghome };//userhome+"~"};
                        //commands.add( pt );
                        commands.add(Arrays.asList(cmds));
                    }
                }

                Runnable run = new Runnable() {
                    @Override
                    public void run() {
                        for (String spec : selspec) {
                            Path p = Paths.get(userhome, spec);

                            Map<String, String> env = new HashMap<String, String>();
                            env.put("create", "true");

                            String uristr = "jar:" + geneset.zippath.toUri();
                            URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );
                            final List<Path> lbi = new ArrayList<Path>();
                            try {
                                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                                    Path specdir = root;
                                    Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
                                        @Override
                                        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                                throws IOException {
                                            final Path destFile = Paths.get(specdir.toString(),
                                                    file.toString());
                                            //System.out.printf("Extracting file %s to %s\n", file, destFile);
                                            Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                                            return FileVisitResult.CONTINUE;
                                        }

                                        @Override
                                        public FileVisitResult preVisitDirectory(Path dir,
                                                BasicFileAttributes attrs) throws IOException {
                                            String specdirstr = specdir.toString();
                                            String dirstr = dir.toString();
                                            final Path dirToCreate = specdir
                                                    .resolve(dirstr.substring(userhome.length() + 1));
                                            if (Files.notExists(dirToCreate)) {
                                                System.out.printf("Creating directory %s\n", dirToCreate);
                                                Files.createDirectory(dirToCreate);
                                            }
                                            return FileVisitResult.CONTINUE;
                                        }
                                    });
                                    break;
                                }

                                URI uri = new URI("file://" + userhome + "/" + spec + "/index.html");
                                Desktop.getDesktop().browse(uri);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            } finally {
                                try {
                                    geneset.zipfilesystem.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                ;
                            }
                        }
                    }
                };

                NativeRun nr = new NativeRun(run);
                nr.runProcessBuilder("antismash", commands, new Object[3], false, run, false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));
    windowmenu.getItems().add(runantismash);

    MenuItem runsignalp = new MenuItem("Run signalP");
    runsignalp.setOnAction(actionEvent -> SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                Serifier ser = new Serifier();
                Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

                JTextField host = new JTextField("localhost");
                JOptionPane.showMessageDialog(null, host);

                String username = System.getProperty("user.name");
                String hostname = host.getText();

                /*Path[] pt = null;
                JFileChooser fc = new JFileChooser();
                fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
                if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
                   pt = new Path[3];
                   pt[2] = fc.getSelectedFile().toPath();
                }*/

                List<Object> commands = new ArrayList<Object>();
                //commands.add(genexyplotaction)

                try {
                    Map<String, String> env = new HashMap<String, String>();
                    env.put("create", "true");

                    String uristr = "jar:" + geneset.zippath.toUri();
                    URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );

                    geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                    for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                        for (String spec : selspec) {
                            /*Path specdir = root.resolve(spec+".prodigal.fsa");
                            if( !Files.exists(specdir) ) {
                               if( spec.startsWith("MAT") ) {
                                  specdir = root.resolve(spec+".gbk.aa");
                               } else specdir = root.resolve("fn_"+spec+"_scaffolds.prodigal.fsa");
                            }*/
                            Stream<Gene> genestream = geneset.genelist.stream()
                                    .filter(gene -> spec.equals(gene.getSpecies())
                                            && (gene.tegeval.type == null || gene.tegeval.type.length() == 0));
                            Path sigout = root.resolve(spec + ".signalp");
                            Path[] pt = new Path[] { null, sigout, null };
                            if (hostname.equals("localhost")) {
                                String[] cmds = { "signalp", "-t", "gram-", "-" };
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            } else {
                                Path p = Paths.get(spec + ".signalp");
                                BufferedWriter bw = Files.newBufferedWriter(p, StandardOpenOption.CREATE,
                                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                                genestream.forEachOrdered(gene -> {
                                    try {
                                        gene.writeGeneIdFasta(bw);
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                });
                                bw.close();

                                //Files.copy(specdir, p, StandardCopyOption.REPLACE_EXISTING);

                                String[] cmds = { "scp", spec + ".signalp", hostname + ":~", ";", "ssh",
                                        hostname, "signalp", "-t", "gram-", spec + ".signalp" };
                                //String[] cmds = {"ssh",hostname,"signalp","-t","gram-","-"};
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            }
                        }

                        break;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                Runnable run = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            geneset.zipfilesystem.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ;
                    }
                };

                NativeRun nr = new NativeRun(run);
                nr.runProcessBuilder("signalp", commands, new Object[3], false, run, false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));
    windowmenu.getItems().add(runsignalp);

    MenuItem runtransm = new MenuItem("Run TransM");
    runtransm.setOnAction(actionEvent -> SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                Serifier ser = new Serifier();
                Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

                JTextField host = new JTextField("localhost");
                JOptionPane.showMessageDialog(null, host);

                String username = System.getProperty("user.name");
                String hostname = host.getText();

                /*Path[] pt = null;
                JFileChooser fc = new JFileChooser();
                fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
                if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
                   pt = new Path[3];
                   pt[2] = fc.getSelectedFile().toPath();
                }*/

                List<Object> commands = new ArrayList<>();
                //commands.add(genexyplotaction)

                try {
                    Map<String, String> env = new HashMap<>();
                    env.put("create", "true");

                    String uristr = "jar:" + geneset.zippath.toUri();
                    URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );

                    geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                    for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                        for (String spec : selspec) {
                            /*Path specdir = root.resolve(spec+".prodigal.fsa");
                            if( !Files.exists(specdir) ) {
                               if( spec.startsWith("MAT") ) {
                                  specdir = root.resolve(spec+".gbk.aa");
                               } else specdir = root.resolve("fn_"+spec+"_scaffolds.prodigal.fsa");
                            }*/

                            Stream<Gene> genestream = geneset.genelist.stream()
                                    .filter(gene -> spec.equals(gene.getSpecies())
                                            && (gene.tegeval.type == null || gene.tegeval.type.length() == 0));
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(baos));
                            genestream.forEach(gene -> {
                                try {
                                    gene.writeGeneIdFasta(bw);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            });
                            bw.close();
                            baos.close();
                            String seqs = baos.toString();
                            seqs = seqs.replace('*', 'X');
                            byte[] bb = seqs.getBytes();
                            Path sigout = root.resolve(spec + ".tm");
                            Object[] pt = new Object[] { bb, sigout, null };
                            if (hostname.equals("localhost")) {
                                String[] cmds = { "decodeanhmm", "-f", "/opt/tmhmm-2.0c/lib/TMHMM2.0.options",
                                        "-modelfile", "/opt/tmhmm-2.0c/lib/TMHMM2.0.model" };
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            } else {
                                //Path p = Paths.get(spec+".tm");
                                //Files.copy(specdir, p, StandardCopyOption.REPLACE_EXISTING);

                                String[] cmds = { "ssh", hostname, "decodeanhmm", "-f",
                                        "/opt/tmhmm-2.0c/lib/TMHMM2.0.options", "-modelfile",
                                        "/opt/tmhmm-2.0c/lib/TMHMM2.0.model" };
                                commands.add(pt);
                                commands.add(Arrays.asList(cmds));
                            }
                        }

                        break;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                Runnable run = () -> {
                    try {
                        geneset.zipfilesystem.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ;
                };

                NativeRun nr = new NativeRun(run);
                nr.runProcessBuilder("transm", commands, new Object[3], false, run, false);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }));
    windowmenu.getItems().add(runtransm);

    MenuItem runtrnascan = new MenuItem("tRNAscan");
    runtrnascan.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> {
        try {
            Serifier ser = new Serifier();
            Set<String> selspec = getSelspec(null, geneset.getSpecies(), null);

            JTextField host = new JTextField("localhost");
            JOptionPane.showMessageDialog(null, host);

            String username = System.getProperty("user.name");
            String hostname = host.getText();

            /*Path[] pt = null;
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
            if( fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) {
            pt = new Path[3];
            pt[2] = fc.getSelectedFile().toPath();
            }*/

            List<Object> commands = new ArrayList<>();
            //commands.add(genexyplotaction)

            try {
                Map<String, String> env = new HashMap<>();
                env.put("create", "true");

                String uristr = "jar:" + geneset.zippath.toUri();
                URI zipuri = URI.create(uristr /*.replace("file://", "file:")*/ );

                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                    for (String spec : selspec) {
                        Path specdir = root.resolve(spec + ".fna");
                        if (!Files.exists(specdir)) {
                            if (spec.startsWith("MAT")) {
                                specdir = root.resolve(spec + ".gbk.fna");
                            } else
                                specdir = root.resolve("fn_" + spec + "_scaffolds.fastg");
                        }

                        System.err.println(Files.exists(specdir));

                        Path sigout = root.resolve("trnas.txt");
                        if (hostname.equals("localhost1")) {
                            Path[] pt = new Path[] { specdir, sigout, null };
                            String[] cmds = { "/usr/local/bin/tRNAscan-SE", "-B", "-" };
                            commands.add(pt);
                            commands.add(Arrays.asList(cmds));
                        } else {
                            Path[] pt = new Path[] { null, sigout, null };
                            Path p = Paths.get(spec + ".trnascan");
                            Files.copy(specdir, p, StandardCopyOption.REPLACE_EXISTING);

                            List<String> lcmd;
                            if (hostname.equals("localhost")) {
                                //String[] cmds = {"/usr/local/bin/trnascan-1.4", spec + ".trnascan"};
                                String[] cmds = { "/usr/local/bin/tRNAscan-SE", "-B", spec + ".trnascan" };
                                lcmd = Arrays.asList(cmds);
                            } else {
                                String[] cmds = { "scp", spec + ".trnascan", hostname + ":~", ";", "ssh",
                                        hostname, "trnascan-1.4", spec + ".trnascan" };
                                lcmd = Arrays.asList(cmds);
                                //String[] cmds = {"ssh",hostname,"tRNAscan-SE","-B","-"};
                            }

                            commands.add(pt);
                            commands.add(lcmd);
                        }
                    }

                    break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            Runnable run = () -> {
                try {
                    geneset.zipfilesystem.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ;
            };

            NativeRun nr = new NativeRun(run);
            nr.runProcessBuilder("tRNAscan", commands, new Object[3], false, run, false);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }));
    windowmenu.getItems().add(runtrnascan);

    Menu select = new Menu("Select");
    MenuItem breakpointselAction = new MenuItem("Select breakpoints");
    breakpointselAction.setOnAction(actionEvent -> {
        String spec = syncolorcomb.getSelectionModel().getSelectedItem();

        int rr = 0;
        for (Gene g : geneset.genelist) {
            if (!spec.equals(g.getSpecies()) && g.getSpecies().contains("eggert")) {
                Tegeval tv2 = g.tegeval;
                Annotation n2 = tv2.getNext();
                Annotation p2 = tv2.getPrevious();

                GeneGroup gg = g.getGeneGroup();

                if (gg.getName().contains("rhodane")) {
                    System.err.println();
                }

                Teginfo ti = gg.getGenes(spec);
                int msimcount = 0;
                if (ti != null) {
                    for (Tegeval tv1 : ti.tset) {
                        int simcount = 0;

                        Annotation n = tv1.getNext();
                        Annotation p = tv1.getPrevious();

                        GeneGroup ggg = tv1.getGene().getGeneGroup();
                        if (n2 != null) {
                            if (ggg == n2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            Annotation nn2 = n2.getNext();
                            if (nn2 != null) {
                                if (ggg == nn2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }
                        }

                        if (p2 != null) {
                            if (ggg == p2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            Annotation pp2 = p2.getPrevious();
                            if (pp2 != null) {
                                if (ggg == pp2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }
                        }

                        if (n != null) {
                            GeneGroup ngg = n.getGene().getGeneGroup();

                            if (ngg == tv2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            if (n2 != null) {
                                if (ngg == n2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            if (p2 != null) {
                                if (ngg == p2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            Annotation nn = n.getNext();
                            if (nn != null) {
                                ngg = nn.getGene().getGeneGroup();

                                if (ngg == tv2.getGene().getGeneGroup()) {
                                    simcount++;
                                }

                                if (n2 != null) {
                                    if (ngg == n2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }

                                if (p2 != null) {
                                    if (ngg == p2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }
                            }
                        }

                        if (p != null) {
                            GeneGroup pgg = p.getGene().getGeneGroup();

                            if (pgg == tv2.getGene().getGeneGroup()) {
                                simcount++;
                            }

                            if (n2 != null) {
                                if (pgg == n2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            if (p2 != null) {
                                if (pgg == p2.getGene().getGeneGroup()) {
                                    simcount++;
                                }
                            }

                            Annotation pp = p.getPrevious();
                            if (pp != null) {
                                pgg = pp.getGene().getGeneGroup();

                                if (pgg == tv2.getGene().getGeneGroup()) {
                                    simcount++;
                                }

                                if (n2 != null) {
                                    if (pgg == n2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }

                                if (p2 != null) {
                                    if (pgg == p2.getGene().getGeneGroup()) {
                                        simcount++;
                                    }
                                }
                            }
                        }

                        //double rat = GeneCompare.invertedGradientRatio(spec, contigs, -1.0, gg, tv);
                        if (simcount >= msimcount) {
                            //tv = tv1;
                            msimcount = simcount;
                        }

                        //double ratio = GeneCompare.invertedGradientRatio(spec, contigs, -1.0, gg, tv);
                        //GeneCompare.gradientColor();
                    }

                    if (msimcount < 2) {
                        gtable.getSelectionModel().select(g);
                    }
                }
            }
            rr++;
        }
        /*List<Sequence> contigs = geneset.speccontigMap.get( spec );
        for( Sequence c : contigs ) {
           for( Annotation ann : c.annset ) {
          Tegeval tv = (Tegeval)ann;
                  
           }
        }*/
    });
    MenuItem saveselAction = new MenuItem("Save selection");
    saveselAction.setOnAction(actionEvent -> {
        /*int[] rr = table.getSelectedRows();
        if( rr.length > 0 ) {
           String val = Integer.toString( table.convertRowIndexToModel(rr[0]) );
           for( int i = 1; i < rr.length; i++ ) {
              val += ","+table.convertRowIndexToModel(rr[i]);
           }
           String selname = JOptionPane.showInputDialog("Selection name");
           if( comp instanceof Applet ) {
              try {
          ((GeneSetHead)comp).saveSel( selname, val);
              } catch (Exception e1) {
          e1.printStackTrace();
              }
           }
        }*/
    });
    select.getItems().add(breakpointselAction);
    select.getItems().add(saveselAction);
    select.getItems().add(new SeparatorMenuItem());

    MenuItem showall = new MenuItem("Show all");
    showall.setOnAction(actionEvent -> {
        genefilterset.clear();
        updateFilter(table, label);
    });
    select.getItems().add(showall);
    MenuItem croptosel = new MenuItem("Crop to selection");
    croptosel.setOnAction(actionEvent -> {
        Set<GeneGroup> selitems = new HashSet<>(table.getSelectionModel().getSelectedItems());
        filteredData.setPredicate(p -> selitems.contains(p));
    });
    select.getItems().add(croptosel);
    MenuItem croptoinvsel = new MenuItem("Crop to inverted selection");
    croptoinvsel.setOnAction(actionEvent -> {
        genefilterset.clear();
        for (int i = 0; i < table.getItems().size(); i++) {
            if (!table.getSelectionModel().isSelected(i)) {
                genefilterset.add(i);
            }
        }
        updateFilter(table, label);
    });
    select.getItems().add(croptoinvsel);
    MenuItem removesel = new MenuItem("Remove selection");
    removesel.setOnAction(actionEvent -> {
        // genefilterset.clear();
        //int[] rr = table.getSelectedRows();
        if (genefilterset.isEmpty()) {
            Set<Integer> ii = new HashSet<Integer>();
            for (int r : table.getSelectionModel().getSelectedIndices())
                ii.add(r);
            for (int i = 0; i < geneset.genelist.size(); i++) {
                if (!ii.contains(i))
                    genefilterset.add(i);
            }
        } else {
            for (int r : table.getSelectionModel().getSelectedIndices()) {
                //int mr = table.convertRowIndexToModel(r);
                genefilterset.remove(r);
            }
        }
        updateFilter(table, label);
    });
    select.getItems().add(removesel);
    MenuItem invsel = new MenuItem("Invert selection");
    invsel.setOnAction(actionEvent -> {
        ObservableList<GeneGroup> selitems = table.getSelectionModel().getSelectedItems();
        List<GeneGroup> newsel = new ArrayList<>(filteredData);
        newsel.removeAll(selitems);

        table.getSelectionModel().clearSelection();
        newsel.stream().forEach(gg -> table.getSelectionModel().select(gg));

        // genefilterset.clear();
        //int[] rr = table.getSelectedRows();
        /*Set<Integer> iset = new HashSet<>();
        for( int r : table.getSelectionModel().getSelectedIndices() ) {
           iset.add( r );
        }
        table.getSelectionModel().clearSelection();
        for (int r = 0; r < table.getItems().size(); r++) {
           if( !iset.contains(r) ) table.getSelectionModel().select(r);
           /*if (table.isRowSelected(r))
          table.removeRowSelectionInterval(r, r);
           else
          table.addRowSelectionInterval(r, r);
        }*/
    });
    select.getItems().add(invsel);
    //select.addSeparator();
    select.getItems().add(new SeparatorMenuItem());
    MenuItem selsinglemult = new MenuItem("Select single copy genes found in multiple strains");
    selsinglemult.setOnAction(actionEvent -> {
        Set<String> specset = getSelspec(GeneSetHead.this, geneset.specList);
        for (GeneGroup gg : geneset.allgenegroups) {
            Set<String> checkspec = new HashSet<String>(gg.species.keySet());
            checkspec.retainAll(specset);
            if (gg.getCommonTag() == null && checkspec.size() > 1
                    && gg.getTegevals().size() == gg.species.size()) {//gg.getTegevals(checkspec).size() == checkspec.size() ) {
                table.getSelectionModel().select(gg);
                //table.setro
            }
        }
    });
    select.getItems().add(selsinglemult);
    MenuItem selsinglemultstrain = new MenuItem(
            "Select single copy genes in accessory genome of multiple strains");
    selsinglemultstrain.setOnAction(actionEvent -> {
        Set<String> specset = getSelspec(GeneSetHead.this, geneset.specList);
        for (GeneGroup gg : geneset.allgenegroups) {
            Set<String> checkspec = new HashSet<String>(gg.species.keySet());
            checkspec.retainAll(specset);
            if (gg.getCommonTag() == null && checkspec.size() > 1 && checkspec.size() < specset.size()
                    && gg.getTegevals().size() == gg.species.size()) {//gg.getTegevals(checkspec).size() == checkspec.size() ) {
                table.getSelectionModel().select(gg);
                //table.setro
            }
        }
    });
    select.getItems().add(selsinglemultstrain);

    MenuItem selsinglecopygenes = new MenuItem("Select single copy genes");
    selsinglecopygenes.setOnAction(actionEvent -> {
        Set<String> specset = getSelspec(GeneSetHead.this, geneset.specList);
        for (GeneGroup gg : geneset.allgenegroups) {
            if (gg.getTegevals().size() == gg.species.size()) {
                table.getSelectionModel().select(gg);
                //table.setro
            }
        }
    });
    select.getItems().add(selsinglecopygenes);
    MenuItem selduplgenes = new MenuItem("Select duplicated genes");
    selduplgenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            int cnt = 0;
            for (String spec : gg.species.keySet()) {
                Teginfo ti = gg.species.get(spec);
                if (ti.tset.size() == 2) {
                    List<Tegeval> ta = new ArrayList<Tegeval>(ti.tset);
                    if (ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1))
                        cnt++;
                }
            }
            if ((float) cnt / (float) gg.species.size() > 0.7) {
                table.getSelectionModel().select(gg);
            }
        }
    });
    select.getItems().add(selduplgenes);
    MenuItem seltriplgenes = new MenuItem("Select triplicated genes");
    seltriplgenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            int cnt = 0;
            for (String spec : gg.species.keySet()) {
                Teginfo ti = gg.species.get(spec);
                if (ti.tset.size() == 3) {
                    List<Tegeval> ta = new ArrayList<Tegeval>(ti.tset);
                    if ((ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1))
                            && (ta.get(1).getNext() == ta.get(2) || ta.get(1).getPrevious() == ta.get(2)))
                        cnt++;
                }
            }
            if ((float) cnt / (float) gg.species.size() > 0.7) {
                table.getSelectionModel().select(gg);
            }
        }
    });
    select.getItems().add(seltriplgenes);

    MenuItem selplasmidgenes = new MenuItem("Select plasmid genes");
    selplasmidgenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            if (gg.isOnAnyPlasmid()) {
                table.getSelectionModel().select(gg);
            }
            /*int cnt = 0;
            for( String spec : gg.species.keySet() ) {
               Teginfo ti = gg.species.get( spec );
               if( ti.tset.size() == 3 ) {
             List<Tegeval> ta = new ArrayList<Tegeval>( ti.tset );
             if( (ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1)) && (ta.get(1).getNext() == ta.get(2) || ta.get(1).getPrevious() == ta.get(2))) cnt++;
               }
            }
            if( (float)cnt / (float)gg.species.size() > 0.7 ) {
               int r = table.convertRowIndexToView(gg.index);
               table.addRowSelectionInterval(r, r);
            }*/
        }
    });
    select.getItems().add(selplasmidgenes);

    MenuItem selectphagegenes = new MenuItem("Select phage genes");
    selectphagegenes.setOnAction(actionEvent -> {
        for (GeneGroup gg : geneset.allgenegroups) {
            if (gg.isInAnyPhage()) {
                table.getSelectionModel().select(gg);
            }
            /*int cnt = 0;
            for( String spec : gg.species.keySet() ) {
               Teginfo ti = gg.species.get( spec );
               if( ti.tset.size() == 3 ) {
             List<Tegeval> ta = new ArrayList<Tegeval>( ti.tset );
             if( (ta.get(0).getNext() == ta.get(1) || ta.get(0).getPrevious() == ta.get(1)) && (ta.get(1).getNext() == ta.get(2) || ta.get(1).getPrevious() == ta.get(2))) cnt++;
               }
            }
            if( (float)cnt / (float)gg.species.size() > 0.7 ) {
               int r = table.convertRowIndexToView(gg.index);
               table.addRowSelectionInterval(r, r);
            }*/
        }
    });
    select.getItems().add(selectphagegenes);
    select.getItems().add(new SeparatorMenuItem());
    MenuItem selectsharingaction = new MenuItem("Select sharing");
    selectsharingaction.setOnAction(actionEvent -> {
        RadioButton panbtn = new RadioButton("Pan");
        RadioButton corebtn = new RadioButton("Core");
        RadioButton blehbtn = new RadioButton("Only in");
        ToggleGroup tg = new ToggleGroup();
        panbtn.setToggleGroup(tg);
        corebtn.setToggleGroup(tg);
        blehbtn.setToggleGroup(tg);

        HBox sp = new HBox();
        sp.getChildren().add(panbtn);
        sp.getChildren().add(corebtn);
        sp.getChildren().add(blehbtn);
        Scene scene = new Scene(sp);

        //FlowLayout flowlayout = new FlowLayout();
        final JFXPanel c = new JFXPanel();
        c.setScene(scene);

        /*Group  root  =  new  Group();
          Scene  scene  =  new  Scene(root, javafx.scene.paint.Color.ALICEBLUE);
          root.getChildren().add(panbtn);
          root.getChildren().add(corebtn);
          root.getChildren().add(blehbtn);
        JFXPanel fxpanel = new JFXPanel();
        fxpanel.setScene( scene );*/
        //bg.add( panbtn );
        //bg.add( corebtn );
        //bg.add( blehbtn );
        corebtn.setSelected(true);
        //Object[] objs = new Object[] { panbtn, corebtn };
        //JOptionPane.showMessageDialog( geneset, objs, "Select id types", JOptionPane.PLAIN_MESSAGE );

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final List<String> species = geneset.getSpecies();
                TableModel model = new TableModel() {
                    @Override
                    public int getRowCount() {
                        return species.size();
                    }

                    @Override
                    public int getColumnCount() {
                        return 1;
                    }

                    @Override
                    public String getColumnName(int columnIndex) {
                        return null;
                    }

                    @Override
                    public Class<?> getColumnClass(int columnIndex) {
                        return String.class;
                    }

                    @Override
                    public boolean isCellEditable(int rowIndex, int columnIndex) {
                        return false;
                    }

                    @Override
                    public Object getValueAt(int rowIndex, int columnIndex) {
                        return species.get(rowIndex);
                    }

                    @Override
                    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
                    }

                    @Override
                    public void addTableModelListener(TableModelListener l) {
                    }

                    @Override
                    public void removeTableModelListener(TableModelListener l) {
                    }
                };
                JTable table = new JTable(model);
                table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                JScrollPane scroll = new JScrollPane(table);

                Object[] objs = new Object[] { scroll, c };
                JOptionPane.showMessageDialog(comp, objs);

                final Set<String> specs = new HashSet<String>();
                int[] rr = table.getSelectedRows();
                for (int r : rr) {
                    String spec = (String) table.getValueAt(r, 0);
                    specs.add(spec);
                }

                Platform.runLater(new Runnable() {
                    public void run() {
                        for (GeneGroup gg : geneset.allgenegroups) {
                            if (blehbtn.isSelected()) {
                                Set<String> ss = new HashSet<String>(gg.species.keySet());
                                ss.removeAll(specs);
                                if (ss.size() == 0) {
                                    GeneSetHead.this.table.getSelectionModel().select(gg);
                                }
                            } else if (gg.species.keySet().containsAll(specs)
                                    && (panbtn.isSelected() || specs.size() == gg.species.size())) {
                                GeneSetHead.this.table.getSelectionModel().select(gg);
                            }
                        }
                    }
                });
            }
        });
    });
    select.getItems().add(selectsharingaction);
    MenuItem selectdirtyaction = new MenuItem("Select dirty");
    selectdirtyaction.setOnAction(actionEvent -> {
        if (!isGeneview()) {
            int i = 0;
            for (GeneGroup gg : geneset.allgenegroups) {
                if (gg.containsDirty()) {
                    table.getSelectionModel().select(gg);
                }
                i++;
            }
        }
    });
    select.getItems().add(selectdirtyaction);
    MenuItem selectdesignationaction = new MenuItem("Select designation");
    selectdesignationaction.setOnAction(actionEvent -> {
        JComboBox<String> descombo = new JComboBox<String>(
                geneset.deset.toArray(new String[geneset.deset.size()]));
        descombo.insertItemAt("", 0);
        descombo.setSelectedIndex(0);

        JOptionPane.showMessageDialog(GeneSetHead.this, descombo);
        String seldes = (String) descombo.getSelectedItem();
        if (!isGeneview()) {
            int i = 0;
            for (GeneGroup gg : geneset.allgenegroups) {
                if (gg.genes != null)
                    for (Gene g : gg.genes) {
                        if (seldes.equals(g.tegeval.designation)) {
                            table.getSelectionModel().select(gg);
                        }
                    }
                i++;
            }
        }
    });
    select.getItems().add(selectdesignationaction);

    MenuItem blastselect = new MenuItem("Blast select");
    blastselect.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blast(false)));
    select.getItems().add(blastselect);

    MenuItem blastxselect = new MenuItem("Blastx select");
    blastxselect.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blast(true)));
    select.getItems().add(blastxselect);

    MenuItem blastnselect = new MenuItem("Blastn select");
    blastnselect.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blastn(true)));
    select.getItems().add(blastnselect);

    MenuItem blastsearch = new MenuItem("Blastn search");
    blastsearch.setOnAction(actionEvent -> SwingUtilities.invokeLater(() -> blastn(false)));
    select.getItems().add(blastsearch);

    menubar.getMenus().add(file);
    menubar.getMenus().add(edit);
    menubar.getMenus().add(view);
    menubar.getMenus().add(sequencemenu);
    menubar.getMenus().add(windowmenu);
    menubar.getMenus().add(select);
    menubar.getMenus().add(help);

    if (comp != null) {
        final Window window = SwingUtilities.windowForComponent(comp);
        initFSKeyListener(window);
        if (comp instanceof JFrame || window instanceof JFrame) {
            JFrame frame = (JFrame) (window == null ? comp : window);
            if (!frame.isResizable())
                frame.setResizable(true);

            frame.addKeyListener(keylistener);
            frame.setJMenuBar(jmenubar);
        }
    }

    final Button jb = new Button("Atlas");
    jb.setOnAction(event -> {
        try {
            URL url = new URL("file:///home/sigmar/workspace/distann/bin/circle.html");
            GeneSetHead.this.getAppletContext().showDocument(url, "_blank");
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
    });

    try {
        newSoft(jb, comp, genetable, upper, lower, toolbar, btoolbar, GeneSetHead.this, selcomb);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (comp != null) {
        if (comp instanceof Applet)
            try {
                ((GeneSetHead) comp).saveSel(null, null);
            } catch (NoSuchMethodError | Exception e1) {
                e1.printStackTrace();
            }
        //comp.add( cc );
    }
}