Example usage for javafx.scene.control ContextMenu ContextMenu

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

Introduction

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

Prototype

public ContextMenu() 

Source Link

Document

Create a new ContextMenu

Usage

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

private void initialize() {

    model = new TMATableModel();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    pane.setCenter(mdTablePane);

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

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

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

    scene = new Scene(pane);

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

}

From source file:com.chart.SwingChart.java

/**
 * /*ww  w.  j  a  v  a  2  s  .c o m*/
 * @param name Chart name
 * @param parent Skeleton parent
 * @param axes Configuration of axes
 * @param abcissaName Abcissa name
 */
public SwingChart(String name, final Skeleton parent, List<AxisChart> axes, String abcissaName) {
    this.skeleton = parent;
    this.axes = axes;
    this.name = name;

    this.abcissaFormat = NumberFormat.getInstance(Locale.getDefault());
    this.ordinateFormat = NumberFormat.getInstance(Locale.getDefault());

    plot = new XYPlot();
    plot.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strChartBackgroundColor)));
    plot.setDomainGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setRangeGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    abcissaAxis = new NumberAxis(abcissaName);
    ((NumberAxis) abcissaAxis).setAutoRangeIncludesZero(false);
    abcissaAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setAutoRange(true);
    abcissaAxis.setLowerMargin(0.0);
    abcissaAxis.setUpperMargin(0.0);
    abcissaAxis.setTickLabelsVisible(true);
    abcissaAxis.setLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));
    abcissaAxis.setTickLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));

    plot.setDomainAxis(abcissaAxis);

    for (int i = 0; i < axes.size(); i++) {
        AxisChart categoria = axes.get(i);
        addAxis(categoria.getName());

        for (int j = 0; j < categoria.configSerieList.size(); j++) {
            SimpleSeriesConfiguration cs = categoria.configSerieList.get(j);
            addSeries(categoria.getName(), cs);
        }
    }
    chart = new JFreeChart("", new Font("SansSerif", Font.BOLD, 16), plot, false);

    chart.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
            BorderFactory.createLineBorder(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)))));

    chartPanel.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escape");
    chartPanel.getActionMap().put("escape", new AbstractAction() {

        @Override
        public void actionPerformed(java.awt.event.ActionEvent e) {
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                XYDataset test = plot.getDataset(i);
                XYItemRenderer r = plot.getRenderer(i);
                r.removeAnnotations();
            }
        }
    });

    chartPanel.addChartMouseListener(cml = new ChartMouseListener() {
        @Override
        public void chartMouseClicked(ChartMouseEvent event) {
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent event) {
            try {
                XYItemEntity xyitem = (XYItemEntity) event.getEntity(); // get clicked entity
                XYDataset dataset = (XYDataset) xyitem.getDataset(); // get data set    
                double x = dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem());
                double y = dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem());

                final XYPlot plot = chart.getXYPlot();
                for (int i = 0; i < plot.getDatasetCount(); i++) {
                    XYDataset test = plot.getDataset(i);
                    XYItemRenderer r = plot.getRenderer(i);
                    r.removeAnnotations();
                    if (test == dataset) {
                        NumberAxis ejeOrdenada = AxesList.get(i);
                        double y_max = ejeOrdenada.getUpperBound();
                        double y_min = ejeOrdenada.getLowerBound();
                        double x_max = abcissaAxis.getUpperBound();
                        double x_min = abcissaAxis.getLowerBound();
                        double angulo;
                        if (y > (y_max + y_min) / 2 && x > (x_max + x_min) / 2) {
                            angulo = 3.0 * Math.PI / 4.0;
                        } else if (y > (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                            angulo = 1.0 * Math.PI / 4.0;
                        } else if (y < (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                            angulo = 7.0 * Math.PI / 4.0;
                        } else {
                            angulo = 5.0 * Math.PI / 4.0;
                        }

                        CircleDrawer cd = new CircleDrawer((Color) r.getSeriesPaint(xyitem.getSeriesIndex()),
                                new BasicStroke(2.0f), null);
                        //XYAnnotation bestBid = new XYDrawableAnnotation(dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), 11, 11, cd);
                        String txt = "X:" + abcissaFormat.format(x) + ", Y:" + ordinateFormat.format(y);
                        XYPointerAnnotation anotacion = new XYPointerAnnotation(txt,
                                dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()),
                                dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), angulo);
                        anotacion.setTipRadius(10.0);
                        anotacion.setBaseRadius(35.0);
                        anotacion.setFont(new Font("SansSerif", Font.PLAIN, 10));

                        if (Long.parseLong((strChartBackgroundColor.replace("#", "")), 16) > 0xffffff / 2) {
                            anotacion.setPaint(Color.black);
                            anotacion.setArrowPaint(Color.black);
                        } else {
                            anotacion.setPaint(Color.white);
                            anotacion.setArrowPaint(Color.white);
                        }

                        //bestBid.setPaint((Color) r.getSeriesPaint(xyitem.getSeriesIndex()));
                        r.addAnnotation(anotacion);
                    }
                }

                //LabelValorVariable.setSize(LabelValorVariable.getPreferredSize());
            } catch (NullPointerException | ClassCastException ex) {

            }
        }
    });

    chartPanel.setPopupMenu(null);
    chartPanel.setBackground(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    SwingNode sn = new SwingNode();
    sn.setContent(chartPanel);
    chartFrame = new VBox();
    chartFrame.getChildren().addAll(sn, legendFrame);
    VBox.setVgrow(sn, Priority.ALWAYS);
    VBox.setVgrow(legendFrame, Priority.NEVER);

    chartFrame.getStylesheets().addAll(SwingChart.class.getResource("overlay-chart.css").toExternalForm());

    legendFrame.setStyle("marco: " + strBackgroundColor + ";-fx-background-color: marco;");

    MenuItem mi;
    mi = new MenuItem("Print");
    mi.setOnAction((ActionEvent t) -> {
        print(chartFrame);
    });
    contextMenuList.add(mi);

    sn.setOnMouseClicked((MouseEvent t) -> {
        if (menu != null) {
            menu.hide();
        }
        if (t.getClickCount() == 2) {
            backgroundEdition();
        }
    });

    mi = new MenuItem("Copy to clipboard");
    mi.setOnAction((ActionEvent t) -> {
        copyClipboard(chartFrame);
    });
    contextMenuList.add(mi);

    mi = new MenuItem("Export values");
    mi.setOnAction((ActionEvent t) -> {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Export to file");
        fileChooser.getExtensionFilters()
                .addAll(new FileChooser.ExtensionFilter("Comma Separated Values", "*.csv"));

        Window w = null;
        try {
            w = parent.getScene().getWindow();
        } catch (NullPointerException e) {

        }
        File file = fileChooser.showSaveDialog(w);
        if (file != null) {
            export(file);
        }
    });
    contextMenuList.add(mi);

    chartFrame.setOnContextMenuRequested((ContextMenuEvent t) -> {
        if (menu != null) {
            menu.hide();
        }
        menu = new ContextMenu();
        menu.getItems().addAll(contextMenuList);
        menu.show(chartFrame, t.getScreenX(), t.getScreenY());
    });

}

From source file:com.github.drbookings.ui.controller.MainController.java

private void initTableViewContextMenus() {
    final ContextMenu menu = new ContextMenu();
    final MenuItem mi1 = new MenuItem("Delete");
    final MenuItem mi2 = new MenuItem("Add");
    final MenuItem mi3 = new MenuItem("Modify");
    mi1.setOnAction(event -> {/*from  w  w  w.j a  v  a2s  . c  o  m*/
        Platform.runLater(() -> deleteSelected());
    });
    mi2.setOnAction(event -> {
        Platform.runLater(() -> addBooking());
    });
    mi3.setOnAction(event -> {
        Platform.runLater(() -> showModifyBookingDialog());
    });
    menu.getItems().addAll(mi2, mi1, mi3);

    tableView.setContextMenu(menu);
    tableView.addEventHandler(MouseEvent.MOUSE_CLICKED, t -> {
        if (t.getButton() == MouseButton.SECONDARY) {
            menu.show(tableView, t.getScreenX(), t.getScreenY());
        }
    });
}

From source file:ninja.javafx.smartcsv.fx.SmartCSVController.java

private ContextMenu contextMenuForColumn(String header) {
    ContextMenu contextMenu = new ContextMenu();
    MenuItem editColumnRulesMenuItem = new MenuItem(resourceBundle.getString("context.menu.edit.column.rules"));
    bindMenuItemsToContentExistence(currentConfigFile, editColumnRulesMenuItem);
    editColumnRulesMenuItem.setOnAction(e -> showValidationEditor(header));
    contextMenu.getItems().addAll(editColumnRulesMenuItem);
    return contextMenu;
}

From source file:qupath.lib.gui.panels.survival.KaplanMeierDisplay.java

@SuppressWarnings("unchecked")
private void generatePlot() {

    KaplanMeierDisplay.ScoreData newScoreData = scoreData;

    // If we have a hierarchy, update the scores with the most recent data
    if (hierarchy != null) {
        List<TMACoreObject> cores = PathObjectTools.getTMACoreObjects(hierarchy, false);
        double[] survival = new double[cores.size()];
        boolean[] censored = new boolean[cores.size()];
        double[] scores = new double[cores.size()];

        //            // Optionally sort by scores... helps a bit when debugging e.g. p-values, Hazard ratios etc.
        //            cores.sort((c1, c2) -> Double.compare(c1.getMeasurementList().getMeasurementValue(scoreColumn), c2.getMeasurementList().getMeasurementValue(scoreColumn)));

        //            scoreColumn = "Positive %";
        //         scoreColumn = "RoughScore";
        for (int i = 0; i < cores.size(); i++) {
            TMACoreObject core = cores.get(i);
            MeasurementList ml = core.getMeasurementList();
            survival[i] = core.getMeasurementList().getMeasurementValue(survivalColumn);
            double censoredValue = core.getMeasurementList().getMeasurementValue(censoredColumn);
            boolean hasCensoredValue = !Double.isNaN(censoredValue)
                    && (censoredValue == 0 || censoredValue == 1);
            censored[i] = censoredValue != 0;
            if (!hasCensoredValue) {
                // If we don't have a censored value, ensure we mask out everything else
                scores[i] = Double.NaN;
                survival[i] = Double.NaN;
            } else if (ml.containsNamedMeasurement(scoreColumn))
                // Get the score if we can
                scores[i] = ml.getMeasurementValue(scoreColumn);
            else {
                //               // Try to compute score if we need to
                //               Map<String, Number> map = ROIMeaningfulMeasurements.getPathClassSummaryMeasurements(core.getChildObjects(), true);
                //               Number value = map.get(scoreColumn);
                //               if (value == null)
                scores[i] = Double.NaN;
                //               else
                //                  scores[i] = value.doubleValue();
            }// w w w.  ja v a 2s .c o  m
        }
        // Mask out any scores that don't have associated survival data
        for (int i = 0; i < survival.length; i++) {
            if (Double.isNaN(survival[i]))
                scores[i] = Double.NaN;
        }

        newScoreData = new ScoreData(scores, survival, censored);

    }

    if (newScoreData == null || newScoreData.scores.length == 0)
        return;

    //         KaplanMeier kmHigh = new KaplanMeier("Above threshold");
    //         KaplanMeier kmLow = new KaplanMeier("Below threshold");

    double[] quartiles = StatisticsHelper.getQuartiles(newScoreData.scores);
    double q1 = quartiles[0];
    double median = quartiles[1];
    double q3 = quartiles[2];
    double[] thresholds;
    if (params != null) {
        Object thresholdMethod = params.getChoiceParameterValue("scoreThresholdMethod");
        if (thresholdMethod.equals("Median")) {
            //               panelParams.setNumericParameterValue("scoreThreshold", median);
            //               ((DoubleParameter)params.getParameters().get("scoreThreshold")).setValue(median); // TODO: UPDATE DIALOG!
            thresholds = new double[] { median };
        } else if (thresholdMethod.equals("Tertiles")) {
            //                  ((DoubleParameter)params.getParameters().get("scoreThreshold")).setValue(median); // TODO: UPDATE DIALOG!
            thresholds = StatisticsHelper.getTertiles(newScoreData.scores);
        } else if (thresholdMethod.equals("Quartiles")) {
            //               ((DoubleParameter)params.getParameters().get("scoreThreshold")).setValue(median); // TODO: UPDATE DIALOG!
            thresholds = new double[] { q1, median, q3 };
        } else if (thresholdMethod.equals("Manual (1)")) {
            thresholds = new double[] { params.getDoubleParameterValue("threshold1") };
        } else if (thresholdMethod.equals("Manual (2)")) {
            thresholds = new double[] { params.getDoubleParameterValue("threshold1"),
                    params.getDoubleParameterValue("threshold2") };
        } else //if (thresholdMethod.equals("Manual (3)")) {
            thresholds = new double[] { params.getDoubleParameterValue("threshold1"),
                    params.getDoubleParameterValue("threshold2"),
                    params.getDoubleParameterValue("threshold3") };
    } else
        thresholds = new double[] { median };

    double minVal = Double.POSITIVE_INFINITY;
    double maxVal = Double.NEGATIVE_INFINITY;
    int numNonNaN = 0;
    for (double d : newScoreData.scores) {
        if (Double.isNaN(d))
            continue;
        if (d < minVal)
            minVal = d;
        if (d > maxVal)
            maxVal = d;
        numNonNaN++;
    }
    boolean scoresValid = maxVal > minVal; // If not this, we don't have valid scores that we can work with

    double maxTimePoint = 0;
    for (double d : newScoreData.survival) {
        if (Double.isNaN(d))
            continue;
        if (d > maxTimePoint)
            maxTimePoint = d;
    }
    if (panelParams != null
            && maxTimePoint > ((IntParameter) params.getParameters().get("censorTimePoints")).getUpperBound()) {
        panelParams.setNumericParameterValueRange("censorTimePoints", 0, Math.ceil(maxTimePoint));
    }

    // Optionally censor at specified time
    double censorThreshold = params == null ? maxTimePoint : params.getIntParameterValue("censorTimePoints");

    // Compute log-rank p-values for *all* possible thresholds
    // Simultaneously determine the threshold that yields the lowest p-value, 
    // resolving ties in favour of a more even split between high/low numbers of events
    boolean pValuesChanged = false;
    if (calculateAllPValues) {
        if (!(pValues != null && pValueThresholds != null && newScoreData.equals(scoreData)
                && censorThreshold == lastPValueCensorThreshold)) {
            Map<Double, Double> mapLogRank = new TreeMap<>();
            Set<Double> setObserved = new HashSet<>();
            for (int i = 0; i < newScoreData.scores.length; i++) {
                Double d = newScoreData.scores[i];
                boolean observed = !newScoreData.censored[i] && newScoreData.survival[i] < censorThreshold;
                if (observed)
                    setObserved.add(d);
                if (mapLogRank.containsKey(d))
                    continue;
                List<KaplanMeierData> kmsTemp = splitByThresholds(newScoreData, new double[] { d },
                        censorThreshold, false);
                //               if (kmsTemp.get(1).nObserved() == 0 || kmsTemp.get(1).nObserved() == 0)
                //                  continue;
                LogRankResult test = LogRankTest.computeLogRankTest(kmsTemp.get(0), kmsTemp.get(1));
                double pValue = test.getPValue();
                //                  double pValue = test.hazardRatio < 1 ? test.hazardRatio : 1.0/test.hazardRatio; // Checking usefulness of Hazard ratios...
                if (!Double.isFinite(pValue))
                    continue;
                //               if (!Double.isFinite(test.getHazardRatio())) {
                ////                  continue;
                //                  pValue = Double.NaN;
                //               }
                mapLogRank.put(d, pValue);
            }
            pValueThresholds = new double[mapLogRank.size()];
            pValues = new double[mapLogRank.size()];
            pValueThresholdsObserved = new boolean[mapLogRank.size()];
            int count = 0;
            for (Entry<Double, Double> entry : mapLogRank.entrySet()) {
                pValueThresholds[count] = entry.getKey();
                pValues[count] = entry.getValue();
                if (setObserved.contains(entry.getKey()))
                    pValueThresholdsObserved[count] = true;
                count++;
            }

            // Find the longest 'significant' stretch
            int maxSigCount = 0;
            int maxSigInd = -1;
            int sigCurrent = 0;
            int[] sigCount = new int[pValues.length];
            for (int i = 0; i < pValues.length; i++) {
                if (pValues[i] < 0.05) {
                    sigCurrent++;
                    sigCount[i] = sigCurrent;
                    if (sigCurrent > maxSigCount) {
                        maxSigCount = sigCurrent;
                        maxSigInd = i;
                    }
                } else
                    sigCurrent = 0;
            }
            if (maxSigCount == 0) {
                logger.info("No p-values < 0.05");
            } else {
                double minThresh = maxSigInd - maxSigCount < 0 ? pValueThresholds[0] - 0.0000001
                        : pValueThresholds[maxSigInd - maxSigCount];
                double maxThresh = pValueThresholds[maxSigInd];
                int nBetween = 0;
                int nBetweenObserved = 0;
                for (int i = 0; i < newScoreData.scores.length; i++) {
                    if (newScoreData.scores[i] > minThresh && newScoreData.scores[i] <= maxThresh) {
                        nBetween++;
                        if (newScoreData.survival[i] < censorThreshold && !newScoreData.censored[i])
                            nBetweenObserved++;
                    }
                }
                logger.info("Longest stretch of p-values < 0.05: {} - {} ({} entries, {} observed)", minThresh,
                        maxThresh, nBetween, nBetweenObserved);
            }

            pValuesSmoothed = new double[pValues.length];
            Arrays.fill(pValuesSmoothed, Double.NaN);
            int n = (pValues.length / 20) * 2 + 1;
            logger.info("Smoothing log-rank test p-values by " + n);
            for (int i = n / 2; i < pValues.length - n / 2; i++) {
                double sum = 0;
                for (int k = i - n / 2; k < i - n / 2 + n; k++) {
                    sum += pValues[k];
                }
                pValuesSmoothed[i] = sum / n;
            }
            //               for (int i = 0; i < pValues.length; i++) {
            //                  double sum = 0;
            //                  for (int k = Math.max(0, i-n/2); k < Math.min(pValues.length, i-n/2+n); k++) {
            //                     sum += pValues[k];
            //                  }
            //                  pValuesSmoothed[i] = sum/n;
            //               }
            //               pValues = pValuesSmoothed;

            lastPValueCensorThreshold = censorThreshold;
            pValuesChanged = true;
        }
    } else {
        lastPValueCensorThreshold = Double.NaN;
        pValueThresholds = null;
        pValues = null;
    }

    //            if (params != null && !Double.isNaN(bestThreshold) && (params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest p-value")))
    if (params != null && (params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest p-value"))) {
        int bestIdx = -1;
        double bestPValue = Double.POSITIVE_INFINITY;
        for (int i = pValueThresholds.length / 10; i < pValueThresholds.length * 9 / 10; i++) {
            if (pValues[i] < bestPValue) {
                bestIdx = i;
                bestPValue = pValues[i];
            }
        }
        thresholds = bestIdx >= 0 ? new double[] { pValueThresholds[bestIdx] } : new double[0];
    } else if (params != null
            && (params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest smoothed p-value"))) {
        int bestIdx = -1;
        double bestPValue = Double.POSITIVE_INFINITY;
        for (int i = pValueThresholds.length / 10; i < pValueThresholds.length * 9 / 10; i++) {
            if (pValuesSmoothed[i] < bestPValue) {
                bestIdx = i;
                bestPValue = pValuesSmoothed[i];
            }
        }
        thresholds = bestIdx >= 0 ? new double[] { pValueThresholds[bestIdx] } : new double[0];
    }

    // Split into different curves using the provided thresholds
    List<KaplanMeierData> kms = splitByThresholds(newScoreData, thresholds, censorThreshold,
            params != null && "Quartiles".equals(params.getChoiceParameterValue("scoreThresholdMethod")));

    //         for (KaplanMeier km : kms)
    //            km.censorAtTime(censorThreshold);
    ////         kmHigh.censorAtTime(censorThreshold);
    ////         kmLow.censorAtTime(censorThreshold);

    //         logger.info("High: " + kmHigh.toString());
    //         logger.info("Low: " + kmLow.toString());
    //         logger.info("Log rank comparison: {}", LogRankTest.computeLogRankTest(kmLow, kmHigh));

    if (plotter == null) {
        plotter = new KaplanMeierChartWrapper(survivalColumn + " time");
        //            plotter.setBorder(BorderFactory.createTitledBorder("Survival plot"));
        //            plotter.getCanvas().setWidth(300);
        //            plotter.getCanvas().setHeight(300);
    }
    KaplanMeierData[] kmArray = new KaplanMeierData[kms.size()];
    plotter.setKaplanMeierCurves(survivalColumn + " time", kms.toArray(kmArray));
    tableModel.setSurvivalCurves(thresholds,
            params != null && params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest p-value"),
            kmArray);

    // Bar width determined using 'Freedman and Diaconis' rule' (but overridden if this gives < 16 bins...)
    double barWidth = (2 * q3 - q1) * Math.pow(numNonNaN, -1.0 / 3.0);
    int nBins = 100;
    if (!Double.isNaN(barWidth))
        barWidth = (int) Math.max(16, Math.ceil((maxVal - minVal) / barWidth));
    Histogram histogram = scoresValid ? new Histogram(newScoreData.scores, nBins) : null;
    if (histogramPanel == null) {
        GridPane paneHistogram = new GridPane();
        histogramPanel = new HistogramPanelFX();
        histogramPanel.getChart().setAnimated(false);
        histogramWrapper = new ThresholdedChartWrapper(histogramPanel.getChart());
        for (ObservableNumberValue val : threshProperties)
            histogramWrapper.addThreshold(val, ColorToolsFX.getCachedColor(240, 0, 0, 128));
        histogramWrapper.getPane().setPrefHeight(150);
        paneHistogram.add(histogramWrapper.getPane(), 0, 0);
        Tooltip.install(histogramPanel.getChart(), new Tooltip("Distribution of scores"));
        GridPane.setHgrow(histogramWrapper.getPane(), Priority.ALWAYS);
        GridPane.setVgrow(histogramWrapper.getPane(), Priority.ALWAYS);

        NumberAxis xAxis = new NumberAxis();
        xAxis.setLabel("Score threshold");
        NumberAxis yAxis = new NumberAxis();
        yAxis.setLowerBound(0);
        yAxis.setUpperBound(1);
        yAxis.setTickUnit(0.1);
        yAxis.setAutoRanging(false);
        yAxis.setLabel("P-value");
        chartPValues = new LineChart<>(xAxis, yAxis);
        chartPValues.setAnimated(false);
        chartPValues.setLegendVisible(false);

        // Make chart so it can be navigated
        ChartToolsFX.makeChartInteractive(chartPValues, xAxis, yAxis);
        pValuesChanged = true;
        Tooltip.install(chartPValues, new Tooltip(
                "Distribution of p-values (log-rank test) comparing low vs. high for all possible score thresholds"));
        //            chartPValues.getYAxis().setAutoRanging(false);
        pValuesWrapper = new ThresholdedChartWrapper(chartPValues);
        for (ObservableNumberValue val : threshProperties)
            pValuesWrapper.addThreshold(val, ColorToolsFX.getCachedColor(240, 0, 0, 128));

        pValuesWrapper.getPane().setPrefHeight(150);
        paneHistogram.add(pValuesWrapper.getPane(), 0, 1);
        GridPane.setHgrow(pValuesWrapper.getPane(), Priority.ALWAYS);
        GridPane.setVgrow(pValuesWrapper.getPane(), Priority.ALWAYS);

        ContextMenu popup = new ContextMenu();
        ChartToolsFX.addChartExportMenu(chartPValues, popup);

        RadioMenuItem miZoomY1 = new RadioMenuItem("0-1");
        miZoomY1.setOnAction(e -> {
            yAxis.setAutoRanging(false);
            yAxis.setUpperBound(1);
            yAxis.setTickUnit(0.2);
        });
        RadioMenuItem miZoomY05 = new RadioMenuItem("0-0.5");
        miZoomY05.setOnAction(e -> {
            yAxis.setAutoRanging(false);
            yAxis.setUpperBound(0.5);
            yAxis.setTickUnit(0.1);
        });
        RadioMenuItem miZoomY02 = new RadioMenuItem("0-0.2");
        miZoomY02.setOnAction(e -> {
            yAxis.setAutoRanging(false);
            yAxis.setUpperBound(0.2);
            yAxis.setTickUnit(0.05);
        });
        RadioMenuItem miZoomY01 = new RadioMenuItem("0-0.1");
        miZoomY01.setOnAction(e -> {
            yAxis.setAutoRanging(false);
            yAxis.setUpperBound(0.1);
            yAxis.setTickUnit(0.05);
        });
        RadioMenuItem miZoomY005 = new RadioMenuItem("0-0.05");
        miZoomY005.setOnAction(e -> {
            yAxis.setAutoRanging(false);
            yAxis.setUpperBound(0.05);
            yAxis.setTickUnit(0.01);
        });
        RadioMenuItem miZoomY001 = new RadioMenuItem("0-0.01");
        miZoomY001.setOnAction(e -> {
            yAxis.setAutoRanging(false);
            yAxis.setUpperBound(0.01);
            yAxis.setTickUnit(0.005);
        });
        ToggleGroup tgZoom = new ToggleGroup();
        miZoomY1.setToggleGroup(tgZoom);
        miZoomY05.setToggleGroup(tgZoom);
        miZoomY02.setToggleGroup(tgZoom);
        miZoomY01.setToggleGroup(tgZoom);
        miZoomY005.setToggleGroup(tgZoom);
        miZoomY001.setToggleGroup(tgZoom);
        Menu menuZoomY = new Menu("Set y-axis range");
        menuZoomY.getItems().addAll(miZoomY1, miZoomY05, miZoomY02, miZoomY01, miZoomY005, miZoomY001);

        MenuItem miCopyData = new MenuItem("Copy chart data");
        miCopyData.setOnAction(e -> {
            String dataString = ChartToolsFX.getChartDataAsString(chartPValues);
            ClipboardContent content = new ClipboardContent();
            content.putString(dataString);
            Clipboard.getSystemClipboard().setContent(content);
        });

        popup.getItems().addAll(miCopyData, menuZoomY);
        chartPValues.setOnContextMenuRequested(e -> {
            popup.show(chartPValues, e.getScreenX(), e.getScreenY());
        });

        for (int col = 0; col < tableModel.getColumnCount(); col++) {
            TableColumn<Integer, String> column = new TableColumn<>(tableModel.getColumnName(col));
            int colNumber = col;
            column.setCellValueFactory(
                    new Callback<CellDataFeatures<Integer, String>, ObservableValue<String>>() {
                        @Override
                        public ObservableValue<String> call(CellDataFeatures<Integer, String> p) {
                            return new SimpleStringProperty(
                                    (String) tableModel.getValueAt(p.getValue(), colNumber));
                        }
                    });

            column.setCellFactory(new Callback<TableColumn<Integer, String>, TableCell<Integer, String>>() {

                @Override
                public TableCell<Integer, String> call(TableColumn<Integer, String> param) {
                    TableCell<Integer, String> cell = new TableCell<Integer, String>() {
                        @Override
                        protected void updateItem(String item, boolean empty) {
                            super.updateItem(item, empty);
                            setText(item);
                            setTooltip(new Tooltip(item));
                        }
                    };
                    return cell;
                }
            });

            table.getColumns().add(column);
        }
        table.setPrefHeight(250);
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        table.maxHeightProperty().bind(table.prefHeightProperty());

        params = new ParameterList();
        //         maxTimePoint = 0;
        //         for (TMACoreObject core : hierarchy.getTMAGrid().getTMACoreList()) {
        //            double os = core.getMeasurementList().getMeasurementValue(TMACoreObject.KEY_OVERALL_SURVIVAL);
        //            double rfs = core.getMeasurementList().getMeasurementValue(TMACoreObject.KEY_RECURRENCE_FREE_SURVIVAL);
        //            if (os > maxTimePoint)
        //               maxTimePoint = os;
        //            if (rfs > maxTimePoint)
        //               maxTimePoint = rfs;
        //         }
        params.addIntParameter("censorTimePoints", "Max censored time", (int) (censorThreshold + 0.5), null, 0,
                (int) Math.ceil(maxTimePoint), "Latest time point beyond which data will be censored");
        //            params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Manual", Arrays.asList("Manual", "Median", "Log-rank test"));
        if (calculateAllPValues)
            // Don't include "Lowest smoothed p-value" - it's not an established method and open to misinterpretation...
            params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Median",
                    Arrays.asList("Manual (1)", "Manual (2)", "Manual (3)", "Median", "Tertiles", "Quartiles",
                            "Lowest p-value"));
        //            params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Median", Arrays.asList("Manual (1)", "Manual (2)", "Manual (3)", "Median", "Tertiles", "Quartiles", "Lowest p-value", "Lowest smoothed p-value"));
        else
            params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Median",
                    Arrays.asList("Manual (1)", "Manual (2)", "Manual (3)", "Median", "Tertiles", "Quartiles"));
        params.addDoubleParameter("threshold1", "Threshold 1",
                thresholds.length > 0 ? thresholds[0] : (minVal + maxVal) / 2, null,
                "Threshold to distinguish between patient groups");
        params.addDoubleParameter("threshold2", "Threshold 2",
                thresholds.length > 1 ? thresholds[1] : (minVal + maxVal) / 2, null,
                "Threshold to distinguish between patient groups");
        params.addDoubleParameter("threshold3", "Threshold 3",
                thresholds.length > 2 ? thresholds[2] : (minVal + maxVal) / 2, null,
                "Threshold to distinguish between patient groups");
        params.addBooleanParameter("showAtRisk", "Show at risk", plotter.getShowAtRisk(),
                "Show number of patients at risk below the plot");
        params.addBooleanParameter("showTicks", "Show censored ticks", plotter.getShowCensoredTicks(),
                "Show ticks to indicate censored data");
        params.addBooleanParameter("showKey", "Show key", plotter.getShowKey(),
                "Show key indicating display of each curve");
        //            params.addBooleanParameter("useColor", "Use color", plotter.getUseColor(), "Show each curve in a different color");
        //         params.addBooleanParameter("useStrokes", "Use strokes", plotter.getUseStrokes(), "Show each curve with a differed line stroke");
        // Hide threshold parameters if threshold can't be used
        if (!scoresValid) {
            //               params.setHiddenParameters(true, "scoreThresholdMethod", "scoreThreshold");
            histogramPanel.getChart().setVisible(false);
        }
        panelParams = new ParameterPanelFX(params);
        panelParams.addParameterChangeListener(this);
        updateThresholdsEnabled();

        for (int i = 0; i < threshProperties.length; i++) {
            String p = "threshold" + (i + 1);
            threshProperties[i].addListener((v, o, n) -> {
                if (interactiveThresholds()) {
                    // Need to do a decent double check with tolerance to text field value changing while typing
                    if (!GeneralTools.almostTheSame(params.getDoubleParameterValue(p), n.doubleValue(), 0.0001))
                        panelParams.setNumericParameterValue(p, n);
                }
            });
        }

        BorderPane paneBottom = new BorderPane();
        TitledPane paneOptions = new TitledPane("Options", panelParams.getPane());
        //            paneOptions.setCollapsible(false);
        Pane paneCanvas = new StackPane();
        paneCanvas.getChildren().add(plotter.getCanvas());

        GridPane paneLeft = new GridPane();
        paneLeft.add(paneOptions, 0, 0);
        paneLeft.add(table, 0, 1);
        GridPane.setHgrow(paneOptions, Priority.ALWAYS);
        GridPane.setHgrow(table, Priority.ALWAYS);
        paneBottom.setLeft(paneLeft);
        paneBottom.setCenter(paneHistogram);

        paneMain.setCenter(paneCanvas);
        paneMain.setBottom(paneBottom);

        paneMain.setPadding(new Insets(10, 10, 10, 10));
    } else if (thresholds.length > 0) {
        // Ensure the sliders/text fields are set sensibly
        if (!GeneralTools.almostTheSame(thresholds[0], params.getDoubleParameterValue("threshold1"), 0.0001)) {
            panelParams.setNumericParameterValue("threshold1", thresholds[0]);
        }
        if (thresholds.length > 1 && !GeneralTools.almostTheSame(thresholds[1],
                params.getDoubleParameterValue("threshold2"), 0.0001)) {
            panelParams.setNumericParameterValue("threshold2", thresholds[1]);
        }
        if (thresholds.length > 2 && !GeneralTools.almostTheSame(thresholds[2],
                params.getDoubleParameterValue("threshold3"), 0.0001)) {
            panelParams.setNumericParameterValue("threshold3", thresholds[2]);
        }
    }

    if (histogram != null) {
        histogramPanel.getHistogramData()
                .setAll(HistogramPanelFX.createHistogramData(histogram, false, (Color) null));
        histogramPanel.getChart().getXAxis().setLabel(scoreColumn);
        histogramPanel.getChart().getYAxis().setLabel("Count");

        ChartToolsFX.addChartExportMenu(histogramPanel.getChart(), null);

        //            histogramWrapper.setVerticalLines(thresholds, ColorToolsFX.getCachedColor(240, 0, 0, 128));
        // Deal with threshold adjustment
        //            histogramWrapper.getThresholds().addListener((Observable o) -> generatePlot());
    }

    if (pValues != null) {
        // TODO: Raise earlier where p-value calculation is
        if (pValuesChanged) {
            ObservableList<XYChart.Data<Number, Number>> data = FXCollections.observableArrayList();
            for (int i = 0; i < pValueThresholds.length; i++) {
                double pValue = pValues[i];
                if (Double.isNaN(pValue))
                    continue;
                data.add(new XYChart.Data<>(pValueThresholds[i], pValue, pValueThresholdsObserved[i]));
            }

            ObservableList<XYChart.Data<Number, Number>> dataSmoothed = null;
            if (pValuesSmoothed != null) {
                dataSmoothed = FXCollections.observableArrayList();
                for (int i = 0; i < pValueThresholds.length; i++) {
                    double pValueSmoothed = pValuesSmoothed[i];
                    if (Double.isNaN(pValueSmoothed))
                        continue;
                    dataSmoothed.add(new XYChart.Data<>(pValueThresholds[i], pValueSmoothed));
                }
            }

            // Don't bother showing the smoothed data... it tends to get in the way...
            //            if (dataSmoothed != null)
            //               chartPValues.getData().setAll(new XYChart.Series<>("P-values", data), new XYChart.Series<>("Smoothed P-values", dataSmoothed));
            //            else
            chartPValues.getData().setAll(new XYChart.Series<>("P-values", data));

            // Add line to show 0.05 significance threshold
            if (pValueThresholds.length > 1) {
                Data<Number, Number> sigData1 = new Data<>(pValueThresholds[0], 0.05);
                Data<Number, Number> sigData2 = new Data<>(pValueThresholds[pValueThresholds.length - 1], 0.05);
                XYChart.Series<Number, Number> dataSignificant = new XYChart.Series<>("Signficance 0.05",
                        FXCollections.observableArrayList(sigData1, sigData2));
                chartPValues.getData().add(dataSignificant);
                sigData1.getNode().setVisible(false);
                sigData2.getNode().setVisible(false);
            }

            //               chartPValues.getData().get(0).getNode().setVisible(true);

            //               pValuesWrapper.clearThresholds();
            for (XYChart.Data<Number, Number> dataPoint : data) {
                if (!Boolean.TRUE.equals(dataPoint.getExtraValue()))
                    dataPoint.getNode().setVisible(false);
            }
            //            if (dataSmoothed != null) {
            //               for (XYChart.Data<Number, Number> dataPoint : dataSmoothed) {
            //                  dataPoint.getNode().setVisible(false);
            //               }
            //               chartPValues.getData().get(1).getNode().setOpacity(0.5);
            //            }

            //               int count = 0;               
            //               for (int i = 0; i < pValueThresholds.length; i++) {
            //                  double pValue = pValues[i];
            //                  if (Double.isNaN(pValue))
            //                     continue;
            //                  boolean observed = pValueThresholdsObserved[i];
            ////                  if (observed)
            ////                     pValuesWrapper.addThreshold(new ReadOnlyDoubleWrapper(pValueThresholds[i]), Color.rgb(0, 0, 0, 0.05));
            //                  
            //                  if (!observed) {
            ////                     StackPane pane = (StackPane)data.get(count).getNode();
            ////                     pane.setEffect(new DropShadow());
            //                     data.get(count).getNode().setVisible(false);
            //                  }
            //                  count++;
            //               }
        }

        for (int i = 0; i < threshProperties.length; i++) {
            if (i < thresholds.length)
                threshProperties[i].set(thresholds[i]);
            else
                threshProperties[i].set(Double.NaN);
        }
        boolean isInteractive = interactiveThresholds();
        histogramWrapper.setIsInteractive(isInteractive);
        pValuesWrapper.setIsInteractive(isInteractive);

        chartPValues.setVisible(true);
    }
    //         else
    //            chartPValues.setVisible(false);

    // Store values for next time
    scoreData = newScoreData;
}

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

private Pane getCustomizeTablePane() {
    TableView<TreeTableColumn<TMAEntry, ?>> tableColumns = new TableView<>();
    tableColumns.setPlaceholder(new Text("No columns available"));
    tableColumns.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    tableColumns.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    SortedList<TreeTableColumn<TMAEntry, ?>> sortedColumns = new SortedList<>(
            table.getColumns().filtered(p -> !p.getText().trim().isEmpty()));
    sortedColumns.setComparator((c1, c2) -> c1.getText().compareTo(c2.getText()));
    tableColumns.setItems(sortedColumns);
    sortedColumns.comparatorProperty().bind(tableColumns.comparatorProperty());
    //      sortedColumns.comparatorProperty().bind(tableColumns.comparatorProperty());

    TableColumn<TreeTableColumn<TMAEntry, ?>, String> columnName = new TableColumn<>("Column");
    columnName.setCellValueFactory(v -> v.getValue().textProperty());
    TableColumn<TreeTableColumn<TMAEntry, ?>, Boolean> columnVisible = new TableColumn<>("Visible");
    columnVisible.setCellValueFactory(v -> v.getValue().visibleProperty());
    //      columnVisible.setCellValueFactory(col -> {
    //         SimpleBooleanProperty prop = new SimpleBooleanProperty(col.getValue().isVisible());
    //         prop.addListener((v, o, n) -> col.getValue().setVisible(n));
    //         return prop;
    //      });/* w ww.j a  va2s. co  m*/
    tableColumns.setEditable(true);
    columnVisible.setCellFactory(v -> new CheckBoxTableCell<>());
    tableColumns.getColumns().add(columnName);
    tableColumns.getColumns().add(columnVisible);
    ContextMenu contextMenu = new ContextMenu();

    Action actionShowSelected = new Action("Show selected", e -> {
        for (TreeTableColumn<?, ?> col : tableColumns.getSelectionModel().getSelectedItems()) {
            if (col != null)
                col.setVisible(true);
            else {
                // Not sure why this happens...?
                logger.trace("Selected column is null!");
            }
        }
    });

    Action actionHideSelected = new Action("Hide selected", e -> {
        for (TreeTableColumn<?, ?> col : tableColumns.getSelectionModel().getSelectedItems()) {
            if (col != null)
                col.setVisible(false);
            else {
                // Not sure why this happens...?
                logger.trace("Selected column is null!");
            }
        }
    });

    contextMenu.getItems().addAll(ActionUtils.createMenuItem(actionShowSelected),
            ActionUtils.createMenuItem(actionHideSelected));
    tableColumns.setContextMenu(contextMenu);
    tableColumns.setTooltip(
            new Tooltip("Show or hide table columns - right-click to change multiple columns at once"));

    BorderPane paneColumns = new BorderPane(tableColumns);
    paneColumns.setBottom(PanelToolsFX.createColumnGridControls(ActionUtils.createButton(actionShowSelected),
            ActionUtils.createButton(actionHideSelected)));

    VBox paneRows = new VBox();

    // Create a box to filter on some metadata text
    ComboBox<String> comboMetadata = new ComboBox<>();
    comboMetadata.setItems(metadataNames);
    comboMetadata.getSelectionModel().getSelectedItem();
    comboMetadata.setPromptText("Select column");
    TextField tfFilter = new TextField();
    CheckBox cbExact = new CheckBox("Exact");
    // Set listeners
    cbExact.selectedProperty().addListener(
            (v, o, n) -> setMetadataTextPredicate(comboMetadata.getSelectionModel().getSelectedItem(),
                    tfFilter.getText(), cbExact.isSelected(), !cbExact.isSelected()));
    tfFilter.textProperty().addListener(
            (v, o, n) -> setMetadataTextPredicate(comboMetadata.getSelectionModel().getSelectedItem(),
                    tfFilter.getText(), cbExact.isSelected(), !cbExact.isSelected()));
    comboMetadata.getSelectionModel().selectedItemProperty().addListener(
            (v, o, n) -> setMetadataTextPredicate(comboMetadata.getSelectionModel().getSelectedItem(),
                    tfFilter.getText(), cbExact.isSelected(), !cbExact.isSelected()));

    GridPane paneMetadata = new GridPane();
    paneMetadata.add(comboMetadata, 0, 0);
    paneMetadata.add(tfFilter, 1, 0);
    paneMetadata.add(cbExact, 2, 0);
    paneMetadata.setPadding(new Insets(10, 10, 10, 10));
    paneMetadata.setVgap(2);
    paneMetadata.setHgap(5);
    comboMetadata.setMaxWidth(Double.MAX_VALUE);
    GridPane.setHgrow(tfFilter, Priority.ALWAYS);
    GridPane.setFillWidth(comboMetadata, Boolean.TRUE);
    GridPane.setFillWidth(tfFilter, Boolean.TRUE);

    TitledPane tpMetadata = new TitledPane("Metadata filter", paneMetadata);
    tpMetadata.setExpanded(false);
    //      tpMetadata.setCollapsible(false);
    Tooltip tooltipMetadata = new Tooltip(
            "Enter text to filter entries according to a selected metadata column");
    Tooltip.install(paneMetadata, tooltipMetadata);
    tpMetadata.setTooltip(tooltipMetadata);
    paneRows.getChildren().add(tpMetadata);

    // Add measurement predicate
    TextField tfCommand = new TextField();
    tfCommand.setTooltip(new Tooltip("Predicate used to filter entries for inclusion"));

    TextFields.bindAutoCompletion(tfCommand, e -> {
        int ind = tfCommand.getText().lastIndexOf("\"");
        if (ind < 0)
            return Collections.emptyList();
        String part = tfCommand.getText().substring(ind + 1);
        return measurementNames.stream().filter(n -> n.startsWith(part)).map(n -> "\"" + n + "\" ")
                .collect(Collectors.toList());
    });

    String instructions = "Enter a predicate to filter entries.\n"
            + "Only entries passing the test will be included in any results.\n"
            + "Examples of predicates include:\n" + "    \"Num Tumor\" > 200\n"
            + "    \"Num Tumor\" > 100 && \"Num Stroma\" < 1000";
    //      labelInstructions.setTooltip(new Tooltip("Note: measurement names must be in \"inverted commands\" and\n" + 
    //            "&& indicates 'and', while || indicates 'or'."));

    BorderPane paneMeasurementFilter = new BorderPane(tfCommand);
    Label label = new Label("Predicate: ");
    label.setAlignment(Pos.CENTER);
    label.setMaxHeight(Double.MAX_VALUE);
    paneMeasurementFilter.setLeft(label);

    Button btnApply = new Button("Apply");
    btnApply.setOnAction(e -> {
        TablePredicate predicateNew = new TablePredicate(tfCommand.getText());
        if (predicateNew.isValid()) {
            predicateMeasurements.set(predicateNew);
        } else {
            DisplayHelpers.showErrorMessage("Invalid predicate",
                    "Current predicate '" + tfCommand.getText() + "' is invalid!");
        }
        e.consume();
    });
    TitledPane tpMeasurementFilter = new TitledPane("Measurement filter", paneMeasurementFilter);
    tpMeasurementFilter.setExpanded(false);
    Tooltip tooltipInstructions = new Tooltip(instructions);
    tpMeasurementFilter.setTooltip(tooltipInstructions);
    Tooltip.install(paneMeasurementFilter, tooltipInstructions);
    paneMeasurementFilter.setRight(btnApply);

    paneRows.getChildren().add(tpMeasurementFilter);

    logger.info("Predicate set to: {}", predicateMeasurements.get());

    VBox pane = new VBox();
    //      TitledPane tpColumns = new TitledPane("Select column", paneColumns);
    //      tpColumns.setMaxHeight(Double.MAX_VALUE);
    //      tpColumns.setCollapsible(false);
    pane.getChildren().addAll(paneColumns, new Separator(), paneRows);
    VBox.setVgrow(paneColumns, Priority.ALWAYS);

    return pane;
}

From source file:snpviewer.SnpViewer.java

private void drawSavedRegions(String chrom) {
    selectionOverlayPane.getChildren().clear();
    if (savedRegions.isEmpty()) {
        selectionOverlayPane.getChildren().add(dragSelectRectangle);
        return;/*from w w w  .  j  a v  a2 s.c  om*/
    }
    for (RegionSummary r : savedRegions) {
        if (r.getChromosome() == null) {
            selectionOverlayPane.getChildren().add(dragSelectRectangle);
            return;
        }
        if (r.getChromosome().equalsIgnoreCase(chrom)) {
            drawRegionSummary(r, chrom);
        }
    }
    int rectCounter = 0;
    for (final Rectangle rect : savedRegionsDisplay) {
        final int counter = rectCounter;
        final ContextMenu scm = new ContextMenu();
        final MenuItem scmItem1 = new MenuItem("Display Flanking SNP IDs");
        scmItem1.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                /* get coordinates of selection and report back
                 * flanking snp ids and coordinates
                 */
                displayFlankingSnpIDs(rect);

            }
        });
        final MenuItem scmItem2 = new MenuItem("Write Region to File");
        scmItem2.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        /* get coordinates of selection and 
                         * write SNPs in region to file
                         */
                        writeRegionToFile(rect);
                    }
                });
            }
        });
        final MenuItem scmItem3 = new MenuItem("Remove this Saved Region");
        scmItem3.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                /* get coordinates of selection and 
                 * write SNPs in region to file
                 */
                removeSavedRegion(counter);

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

        scm.getItems().add(scmItem1);
        scm.getItems().add(scmItem2);
        scm.getItems().add(scmItem3);
        scm.getItems().add(scmItem4);
        scm.getItems().add(scmItem5);
        scm.getItems().add(scmItem6);
        rect.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent e) {
                ocm.hide();

                if (scm.isShowing()) {
                    scm.hide();
                }
                if (e.getButton() == MouseButton.SECONDARY) {
                    if (chromosomeSelector.getSelectionModel().isEmpty()) {
                        for (MenuItem mi : scm.getItems()) {
                            mi.setDisable(true);
                        }
                    } else {
                        for (MenuItem mi : scm.getItems()) {
                            mi.setDisable(false);
                        }
                    }

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

        });
        rect.setVisible(true);
        selectionOverlayPane.getChildren().add(rect);
        rectCounter++;
    }
    selectionOverlayPane.getChildren().add(dragSelectRectangle);
}

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

/**
 * Initializes the controller class.// www  .  j  av a  2 s .  c o  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:org.simmi.GeneSetHead.java

License:asdf

private void showGeneTable(
        /*final Map<String, Gene> genemap, final List<Gene> genelist, 
        final List<Function> funclist, final List<Set<String>> iclusterlist, final List<Set<String>> uclusterlist,
        final Map<Set<String>, ShareNum> specset,*/ final Map<Set<String>, ClusterInfo> clustInfoMap,
        final Button jb, final TableView<Gene> genetable, final TableView<Function> upper,
        final TableView<GeneGroup> lower, final ToolBar toolbar, final ToolBar btoolbar, final Container comp,
        final JApplet applet, final ComboBox<String> selcomblocal) throws IOException {
    //JSplitPane splitpane = new JSplitPane();
    //splitpane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    //splitpane.setDividerLocation(400);
    //JScrollPane scrollpane = new JScrollPane();

    /*table = new JTable() {
       public String getToolTipText(MouseEvent me) {
    Point p = me.getPoint();/* ww w .j  a  v a2 s .c o m*/
    int r = rowAtPoint(p);
    int c = columnAtPoint(p);
    if (r >= 0 && r < super.getRowCount()) {
       Object ret = super.getValueAt(r, c);
       if (ret != null) {
          return ret.toString(); // super.getToolTipText( me );
       }
    }
    return "";
       }
    };*/

    //table.setDragEnabled(true);
    try {
        final DataFlavor df = new DataFlavor("text/plain;charset=utf-8");
        // System.err.println( df.getHumanPresentableName() + " " +
        // df.getPrimaryType() + " " + df.getSubType() + " " +
        // df.getMimeType() );
        // DataFlavor df1 = DataFlavor.getTextPlainUnicodeFlavor();
        // System.err.println( df.getHumanPresentableName() + " " +
        // df.getPrimaryType() + " " + df.getSubType() + " " +
        // df.getMimeType() );
        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 true;
            }

            protected Transferable createTransferable(JComponent c) {
                return new Transferable() {
                    @Override
                    public Object getTransferData(DataFlavor arg0)
                            throws UnsupportedFlavorException, IOException {
                        Map<String, List<Tegeval>> contigs = new HashMap<>();
                        StringBuilder ret = new StringBuilder();
                        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                            Tegeval tv = gg.tegeval;
                            if (!contigs.containsKey(tv.getContshort())) {
                                List<Tegeval> ltv = new ArrayList<>();
                                ltv.add(tv);
                                contigs.put(tv.getContshort().getName(), ltv);
                            } else {
                                List<Tegeval> ltv = contigs.get(tv.getContshort());
                                ltv.add(tv);
                            }
                            /*
                             * ret.append( ">" + tv.cont + " " +
                             * tv.teg + " " + tv.eval + "\n" );
                             * if( tv.dna != null ) { for( int i
                             * = 0; i < tv.dna.length(); i+=70 )
                             * { ret.append(tv.dna.substring( i,
                             * Math.min(i+70,tv.dna.length())
                             * )+"\n"); } }
                             */
                        }
                        for (String cont : contigs.keySet()) {
                            List<Tegeval> tv = contigs.get(cont);
                            String dna = tv.get(0).getSequence();
                            ret.append(">" + cont + "\n"); // + " " + tv.teg
                            // + " " +
                            // tv.eval +
                            // "\n" );
                            if (dna != null) {
                                for (int i = 0; i < dna.length(); i += 70) {
                                    ret.append(dna.substring(i, Math.min(i + 70, dna.length())) + "\n");
                                }
                            }
                        }
                        for (String cont : contigs.keySet()) {
                            List<Tegeval> ltv = contigs.get(cont);
                            ret.append(">" + cont + "\n"); // + " " + tv.teg
                            // + " " +
                            // tv.eval +
                            // "\n" );
                            for (Tegeval tv : ltv) {
                                ret.append("erm\t#0000ff\t" + tv.start + "\t" + tv.stop + "\n");
                            }
                        }

                        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;
                    }
                };
            }

            public boolean importData(TransferHandler.TransferSupport support) {
                Object obj = null;

                System.err.println(support.getDataFlavors().length);
                int b = Arrays.binarySearch(support.getDataFlavors(), DataFlavor.javaFileListFlavor,
                        (o1, o2) -> o1 == o2 ? 1 : 0);

                try {
                    obj = support.getTransferable().getTransferData(DataFlavor.imageFlavor);
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    if (obj != null && obj instanceof File[]) {
                        // File[] ff = (File[])obj;
                        // wbStuff( ff[0].getCanonicalPath() );
                    } else if (obj instanceof Image) {

                    } else {
                        obj = support.getTransferable().getTransferData(DataFlavor.stringFlavor);
                        System.err.println(obj);
                        URL url = null;
                        try {
                            url = new URL((String) obj);
                            Image image = ImageIO.read(url);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return true;
            }
        };
        //table.setTransferHandler(th);
    } catch (ClassNotFoundException e2) {
        e2.printStackTrace();
    }

    final Color darkgreen = new Color(0, 128, 0);
    final Color darkred = new Color(128, 0, 0);
    final Color darkblue = new Color(0, 0, 128);
    final Color darkmag = new Color(128, 0, 128);
    /*table.setDefaultRenderer(Teg.class, new DefaultTableCellRenderer() {
       @Override
       public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component label = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if( value == null ) {
       label.setBackground(Color.white);
    } else {
       cellRender();
    }
    return label;
       }
    });*/

    //table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    //table.setAutoCreateRowSorter(true);
    //scrollpane.setViewportView(table);

    Set<String> current = null;
    Set<String> currentko = null;
    InputStream is = GeneSet.class.getResourceAsStream("/kegg_pathways");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = br.readLine();
    while (line != null) {
        if (line.startsWith(">")) {
            current = new HashSet<>();
            currentko = new HashSet<>();
            geneset.pathwaymap.put(line.substring(1), current);
            geneset.pathwaykomap.put(line.substring(1), currentko);
        } else if (!line.startsWith("K")) {
            if (current != null) {
                String str = line.split("[\t ]+")[0];
                current.add(str);
            }
        } else {
            if (currentko != null) {
                String str = line.split("[\t ]+")[0];
                currentko.add(str);
            }
        }
        line = br.readLine();
    }
    br.close();

    //FileReader fr = new FileReader("/vg454flx/ko2go.txt");
    /*is = GeneSet.class.getResourceAsStream("/ko2go.txt");
    InputStreamReader isr = new InputStreamReader( is );
    br = new BufferedReader( isr );
    line = br.readLine();
    while (line != null) {
       String[] split = line.split(" = ");
       String[] subsplit = split[1].split(" ");
       Set<String> gos = new HashSet<String>();
       for( String go : subsplit ) {
    gos.add( go );
       }
       ko2go.put( split[0], gos );
       line = br.readLine();
    }
    br.close();*/

    final TextField textfield = new TextField();
    //JComponent topcomp = new JComponent() {};
    //topcomp.setLayout(new BorderLayout());
    //topcomp.add(scrollpane);

    textfield.setPrefSize(350, 25);

    final RadioButton search = new RadioButton("Search");
    final RadioButton filter = new RadioButton("Filter");

    ToggleGroup bgsf = new ToggleGroup();
    search.setToggleGroup(bgsf);
    filter.setToggleGroup(bgsf);
    //ButtonGroup bgsf = new ButtonGroup();
    //bgsf.add( search );
    //bgsf.add( filter );

    filter.setSelected(true);

    //ToolBar topcombo = new ToolBar();
    // topcombo.
    // topcombo.setLayout( new FlowLayout() );

    specombo = new ComboBox<>();
    combo = new ComboBox<>();

    specombo.getItems().add("Select blast species");
    combo.getItems().add("Select pathway");
    btoolbar.getItems().add(combo);
    btoolbar.getItems().add(specombo);
    //topcomp.add(topcombo, BorderLayout.SOUTH);

    //JComponent ttopcom = new JComponent() {};
    //ttopcom.setLayout(new FlowLayout());

    /*            frame.setVisible( true );
             }
          };
          AbstractAction   sharenumaction = new AbstractAction("Update share numbers") {
             @Override
             public void actionPerformed(ActionEvent e) {
    Set<String> specs = getSelspec(GeneSetHead.this, specList, null);
    updateShareNum(specs);
             }
          };
          AbstractAction   importgenesymbolaction = new AbstractAction("Import gene symbols") {
             @Override
             public void actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    if( fc.showOpenDialog( GeneSetHead.this ) == JFileChooser.APPROVE_OPTION ) {
       try {
          Map<String,String> env = new HashMap<String,String>();
          env.put("create", "true");
          Path path = zipfile.toPath();
          String uristr = "jar:" + path.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);
                  
          InputStream is = new GZIPInputStream( new FileInputStream( fc.getSelectedFile() ) );
          uni2symbol(new InputStreamReader(is), bw, unimap);
                  
          bw.close();
          //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
          geneset.zipfilesystem.close();
       } catch (IOException e1) {
          e1.printStackTrace();
       }
    }
             }
          };
                  
          AbstractAction   importidmappingaction = new AbstractAction("Id mapping") {
             @Override
             public void actionPerformed(ActionEvent e) {
    JFileChooser fc = new JFileChooser();
    if( fc.showOpenDialog( GeneSetHead.this ) == JFileChooser.APPROVE_OPTION ) {
       try {
          Map<String,String> env = new HashMap<String,String>();
          env.put("create", "true");
          Path path = zipfile.toPath();
          String uristr = "jar:" + path.toUri();
          geneset.zipuri = URI.create( uristr /*.replace("file://", "file:")/ );
          geneset.zipfilesystem = FileSystems.newFileSystem( geneset.zipuri, env );
                  
          Path nf = geneset.zipfilesystem.getPath("/idmapping_short.dat");
          BufferedWriter bw = Files.newBufferedWriter(nf, StandardOpenOption.CREATE);
                  
          InputStream is = new GZIPInputStream( new FileInputStream( fc.getSelectedFile() ) );
          if( unimap != null ) unimap.clear();
          unimap = idMapping(new InputStreamReader(is), bw, 2, 0, refmap, genmap, gimap);
                  
          bw.close();
          //long bl = Files.copy( new ByteArrayInputStream( baos.toByteArray() ), nf, StandardCopyOption.REPLACE_EXISTING );
          geneset.zipfilesystem.close();
       } catch (IOException e1) {
          e1.printStackTrace();
       }
    }
             }
          };
                  
          final JCheckBoxMenuItem checkbox = new JCheckBoxMenuItem();
          checkbox.setAction(new AbstractAction("Sort by location") {
             @Override
             public void actionPerformed(ActionEvent e) {
    Tegeval.locsort = checkbox.isSelected();
             }
          });
          AbstractAction saveselAction = new AbstractAction("Save selection") {
             @Override
             public void actionPerformed(ActionEvent e) {
    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 {
             ((GeneSet)comp).saveSel( selname, val);
          } catch (Exception e1) {
             e1.printStackTrace();
          }
       }
    }
             }
          };
                  
          JMenuBar   menubar = new JMenuBar();
          JMenu      menu = new JMenu("Functions");
          menu.add( importidmappingaction );
          menu.add( functionmappingaction );
          menu.add( importgenesymbolaction );
          menu.add( fetchaction );
          menu.add( blast2action );
          menu.add( sharenumaction );
          menu.addSeparator();
          menu.add( checkbox );
          menu.add( saveselAction );
          menu.addSeparator();
          menu.add( genomestataction );
          menu.add( selectsharingaction );
          menu.add( shuffletreeaction );
          menu.add( presabsaction );
          menu.add( freqdistaction );
          menu.add( gcpaction );
          menu.add( matrixaction );
          menu.add( pancoreaction );
          menu.add( blastaction );
          menu.add( koexportaction );
          menu.add( genomesizeaction );
          menu.add( gcaction );
          menu.add( gcskewaction );
          menu.add( mltreemapaction );
          menu.add( sevenaction );
          menu.add( cogaction );
          menu.add( genexyplotaction );
          menu.add( compareplotaction );
          menu.add( syntenygradientaction );
          menu.add( codregaction );
          menu.add( fetchcoreaction );
          menu.add( loadcontiggraphaction );
          menu.add( selectflankingaction );
          menu.add( showflankingaction );
          menu.add( showcontigsaction );
          menu.add( showunresolved );
          menu.add( genephyl );
                  
          menubar.add( menu );
          ttopcom.add( menubar );
                  
          JMenu      view = new JMenu("View");
          menubar.add( view );
                  
          gb = new JRadioButtonMenuItem( new AbstractAction("Genes") {
             @Override
             public void actionPerformed(ActionEvent e) {
    table.setModel( defaultModel );
             }
          });
          view.add( gb );
          ggb = new JRadioButtonMenuItem( new AbstractAction("Gene groups") {
             @Override
             public void actionPerformed(ActionEvent e) {
    table.setModel( groupModel );
             }
                     
          });
          ButtonGroup   bg = new ButtonGroup();
          bg.add( gb );
          bg.add( ggb );
                  
          ggb.setSelected( true );
                  
          view.add( ggb );*/

    //ttopcom.add( shuffletreebutton );
    //ttopcom.add( presabsbutton );
    //ttopcom.add(freqdistbutton);
    //ttopcom.add(matrixbutton);

    toolbar.getItems().add(textfield);
    toolbar.getItems().add(search);
    toolbar.getItems().add(filter);
    toolbar.getItems().add(label);

    selcomblocal.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        String key = newValue;
        if (((GeneSetHead) comp).selectionMap.containsKey(key)) {
            Set<Integer> val = ((GeneSetHead) comp).selectionMap.get(key);
            if (val != null) {
                table.getSelectionModel().clearSelection();
                for (int i : val) {
                    //int r = table.convertRowIndexToView(i);
                    table.getSelectionModel().select(i);
                }
            } else {
                System.err.println("null " + key);
            }
        } else {
            System.err.println("no " + key);
        }
    });
    toolbar.getItems().add(selcomblocal);

    /*syncolorcomb.addItemListener( new ItemListener() {
       @Override
       public void itemStateChanged(ItemEvent e) {
    String spec = (String)syncolorcomb.getSelectedItem();
    //if( spec.length() > 0 )
       }
    });*/
    toolbar.getItems().add(searchcolcomb);
    toolbar.getItems().add(syncolorcomb);
    //topcomp.add(ttopcom, BorderLayout.NORTH);

    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    table.getSelectionModel().selectedItemProperty().addListener(e -> {
        label.setText(table.getItems().size() + "/" + table.getSelectionModel().getSelectedItems().size());
    });

    gtable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    gtable.getSelectionModel().selectedItemProperty().addListener(e -> {
        label.setText(gtable.getItems().size() + "/" + gtable.getSelectionModel().getSelectedItems().size());
    });

    /*JButton but = new JButton(new AbstractAction("Gene sorter") {
       @Override
       public void actionPerformed(ActionEvent e) {
    try {
       GeneSorter.mynd(genelist, table, "t.scotoductusSA01", contigs);
    } catch (IOException e1) {
       e1.printStackTrace();
    }
       }
    });*/

    final TextField ftextfield = new TextField();
    btoolbar.getItems().add(ftextfield);

    ComboBox<String> scombo = new ComboBox();
    scombo.getItems().add("5S/8S");
    scombo.getItems().add("16S/18S");
    scombo.getItems().add("23S/28S");
    scombo.getSelectionModel().selectedItemProperty().addListener(e -> {
        String name = e.toString().split("/")[0];
        InputStream iss = GeneSet.class.getResourceAsStream("/all" + name + ".fsa");
        InputStreamReader isr = new InputStreamReader(iss);
        BufferedReader brr = new BufferedReader(isr);

        JTextArea textarea = new JTextArea();
        JScrollPane scrollpane = new JScrollPane(textarea);

        try {
            String ln = brr.readLine();
            while (ln != null) {
                textarea.append(ln + "\n");

                ln = brr.readLine();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

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

    Button swsearch = new Button("SW Search");
    swsearch.setOnAction(e -> {
        JComponent c = new JComponent() {
        };
        final JProgressBar pb = new JProgressBar();
        final JTextArea textarea = new JTextArea();
        JButton searchbut = new JButton(new AbstractAction("Blast") {
            @Override
            public void actionPerformed(ActionEvent e) {
                final String fasta = textarea.getText();
                final SmithWater sw = new SmithWater();
                final InputStream is = GeneSet.class.getResourceAsStream("/allthermus.aa");
                new Thread() {
                    public void run() {
                        try {
                            sw.fasta_align(new StringReader(fasta), new InputStreamReader(is), pb);
                            List<SmithWater.ALN> alns = sw.getAlignments();
                            SmithWater.ALN first = null;
                            int count = 0;
                            String result = "";
                            Set<String> regnames = new HashSet<String>();
                            for (SmithWater.ALN aln : alns) {
                                if (first == null) {
                                    first = aln;
                                } else if (aln.getScore() < 3.0f * (first.getScore() / 4.0f))
                                    break;
                                result += aln.toString();
                                regnames.add(aln.getShortDestName());

                                if (++count == 10)
                                    break;
                            }
                            textarea.setText(result);

                            for (Gene g : geneset.genelist) {
                                boolean found = false;
                                Tegeval tv = g.tegeval;
                                if (regnames.contains(tv.name)) {
                                    found = true;
                                    break;
                                }
                                if (found) {
                                    gtable.getSelectionModel().select(g);
                                    break;
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        c.setLayout(new BorderLayout());
        JScrollPane scrollpane = new JScrollPane(textarea);
        c.add(scrollpane);
        c.add(pb, BorderLayout.NORTH);
        c.add(searchbut, BorderLayout.SOUTH);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(c);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });
    btoolbar.getItems().add(swsearch);
    btoolbar.getItems().add(jb);

    TableColumn<GeneGroup, String> namedesccol = new TableColumn("Desc");
    namedesccol.setCellValueFactory(new PropertyValueFactory<>("name"));
    table.getColumns().add(namedesccol);
    TableColumn<GeneGroup, String> origincol = new TableColumn("Origin");
    origincol.setCellValueFactory(new PropertyValueFactory<>("origin"));
    table.getColumns().add(origincol);
    TableColumn<GeneGroup, String> geneidcol = new TableColumn("Genid");
    geneidcol.setCellValueFactory(new PropertyValueFactory<>("genid"));
    table.getColumns().add(geneidcol);
    TableColumn<GeneGroup, String> refidcol = new TableColumn("Refid");
    refidcol.setCellValueFactory(new PropertyValueFactory<>("refid"));
    table.getColumns().add(refidcol);
    TableColumn<GeneGroup, String> unidcol = new TableColumn("Unid");
    unidcol.setCellValueFactory(new PropertyValueFactory<>("unid"));
    table.getColumns().add(unidcol);
    TableColumn<GeneGroup, String> keggidcol = new TableColumn("Keggid");
    keggidcol.setCellValueFactory(new PropertyValueFactory<>("keggid"));
    table.getColumns().add(keggidcol);
    TableColumn<GeneGroup, String> keggpathcol = new TableColumn("Kegg pathway");
    keggpathcol.setCellValueFactory(new PropertyValueFactory<>("keggPathway"));
    table.getColumns().add(keggpathcol);
    TableColumn<GeneGroup, String> kocol = new TableColumn("KO");
    kocol.setCellValueFactory(new PropertyValueFactory<>("ko"));
    table.getColumns().add(kocol);
    TableColumn<GeneGroup, String> ksymbcol = new TableColumn("Ksymbol");
    ksymbcol.setCellValueFactory(new PropertyValueFactory<>("ksymbol"));
    table.getColumns().add(ksymbcol);
    TableColumn<GeneGroup, String> symbcol = new TableColumn("Symbol");
    symbcol.setCellValueFactory(new PropertyValueFactory<>("symbol"));
    table.getColumns().add(symbcol);
    TableColumn<GeneGroup, String> konamecol = new TableColumn("KO name");
    konamecol.setCellValueFactory(new PropertyValueFactory<>("koname"));
    table.getColumns().add(konamecol);
    TableColumn<GeneGroup, String> pbidcol = new TableColumn("Pbid");
    pbidcol.setCellValueFactory(new PropertyValueFactory<>("pbid"));
    table.getColumns().add(pbidcol);
    TableColumn<GeneGroup, String> eccol = new TableColumn("Ec");
    eccol.setCellValueFactory(new PropertyValueFactory<>("ec"));
    table.getColumns().add(eccol);
    TableColumn<GeneGroup, String> cognamecol = new TableColumn("Cog name");
    cognamecol.setCellValueFactory(new PropertyValueFactory<>("cogname"));
    table.getColumns().add(cognamecol);
    TableColumn<GeneGroup, String> cogcol = new TableColumn("Cog");
    cogcol.setCellValueFactory(new PropertyValueFactory<>("cog"));
    table.getColumns().add(cogcol);
    TableColumn<GeneGroup, String> cogannocol = new TableColumn("Cog annotation");
    cogannocol.setCellValueFactory(new PropertyValueFactory<>("coganno"));
    table.getColumns().add(cogannocol);
    TableColumn<GeneGroup, String> cogsymbcol = new TableColumn("Cog symbol");
    cogsymbcol.setCellValueFactory(new PropertyValueFactory<>("cogsymbol"));
    table.getColumns().add(cogsymbcol);
    TableColumn<GeneGroup, String> cazycol = new TableColumn("Cazy");
    cazycol.setCellValueFactory(new PropertyValueFactory<>("cazy"));
    table.getColumns().add(cazycol);
    TableColumn<GeneGroup, String> prescol = new TableColumn("Present in");
    prescol.setCellValueFactory(new PropertyValueFactory<>("presentin"));
    table.getColumns().add(prescol);

    TableColumn<GeneGroup, Integer> groupindcol = new TableColumn("Group index");
    groupindcol.setCellValueFactory(new PropertyValueFactory<GeneGroup, Integer>("groupIndex"));
    table.getColumns().add(groupindcol);
    TableColumn<GeneGroup, Integer> groupcovcol = new TableColumn("Group coverage");
    groupcovcol.setCellValueFactory(new PropertyValueFactory<GeneGroup, Integer>("groupCoverage"));
    table.getColumns().add(groupcovcol);
    TableColumn<GeneGroup, Integer> groupsizecol = new TableColumn("Group size");
    groupsizecol.setCellValueFactory(new PropertyValueFactory<GeneGroup, Integer>("groupGeneCount"));
    table.getColumns().add(groupsizecol);

    TableColumn<GeneGroup, String> locprefcol = new TableColumn("Loc pref");
    locprefcol.setCellValueFactory(new PropertyValueFactory<>("locpref"));
    table.getColumns().add(locprefcol);
    TableColumn<GeneGroup, String> avgcpcol = new TableColumn("Avg GC%");
    avgcpcol.setCellValueFactory(new PropertyValueFactory<>("avggcp"));
    table.getColumns().add(avgcpcol);
    TableColumn<GeneGroup, String> numloccol = new TableColumn("#Loc");
    numloccol.setCellValueFactory(new PropertyValueFactory<>("numloc"));
    table.getColumns().add(numloccol);
    TableColumn<GeneGroup, String> numlocgroupcol = new TableColumn("#Loc group");
    numlocgroupcol.setCellValueFactory(new PropertyValueFactory<>("numlocgroup"));
    table.getColumns().add(numlocgroupcol);

    TableColumn<GeneGroup, ShareNum> sharenumcol = new TableColumn("Sharing number");
    sharenumcol.setCellValueFactory(new PropertyValueFactory<>("sharingNumber"));
    table.getColumns().add(sharenumcol);
    TableColumn<GeneGroup, String> maxcyccol = new TableColumn("Max cyc");
    maxcyccol.setCellValueFactory(new PropertyValueFactory<>("maxCyc"));
    table.getColumns().add(maxcyccol);

    TableColumn<Gene, String> gnamedesccol = new TableColumn("Desc");
    gnamedesccol.setCellValueFactory(new PropertyValueFactory<>("name"));
    gtable.getColumns().add(gnamedesccol);
    TableColumn<Gene, String> gorigincol = new TableColumn("Origin");
    gorigincol.setCellValueFactory(new PropertyValueFactory<>("origin"));
    gtable.getColumns().add(gorigincol);
    TableColumn<Gene, String> ggeneidcol = new TableColumn("Genid");
    ggeneidcol.setCellValueFactory(new PropertyValueFactory<>("genid"));
    gtable.getColumns().add(ggeneidcol);
    TableColumn<Gene, String> grefidcol = new TableColumn("Refid");
    grefidcol.setCellValueFactory(new PropertyValueFactory<>("refid"));
    gtable.getColumns().add(grefidcol);
    TableColumn<Gene, String> gunidcol = new TableColumn("Unid");
    gunidcol.setCellValueFactory(new PropertyValueFactory<>("unid"));
    gtable.getColumns().add(gunidcol);
    TableColumn<Gene, String> gkeggidcol = new TableColumn("Keggid");
    gkeggidcol.setCellValueFactory(new PropertyValueFactory<>("keggid"));
    gtable.getColumns().add(gkeggidcol);
    TableColumn<Gene, String> gkeggpathcol = new TableColumn("Kegg pathway");
    gkeggpathcol.setCellValueFactory(new PropertyValueFactory<>("keggPathway"));
    gtable.getColumns().add(gkeggpathcol);
    TableColumn<Gene, String> gkocol = new TableColumn("KO");
    gkocol.setCellValueFactory(new PropertyValueFactory<>("ko"));
    gtable.getColumns().add(gkocol);
    TableColumn<Gene, String> gksymbcol = new TableColumn("Ksymbol");
    gksymbcol.setCellValueFactory(new PropertyValueFactory<>("ksymbol"));
    gtable.getColumns().add(gksymbcol);
    TableColumn<Gene, String> gsymbcol = new TableColumn("Symbol");
    gsymbcol.setCellValueFactory(new PropertyValueFactory<>("symbol"));
    gtable.getColumns().add(gsymbcol);
    TableColumn<Gene, String> gkonamecol = new TableColumn("KO name");
    gkonamecol.setCellValueFactory(new PropertyValueFactory<>("koname"));
    gtable.getColumns().add(gkonamecol);
    TableColumn<Gene, String> gpbidcol = new TableColumn("Pbid");
    gpbidcol.setCellValueFactory(new PropertyValueFactory<>("pbid"));
    gtable.getColumns().add(gpbidcol);
    TableColumn<Gene, String> geccol = new TableColumn("Ec");
    geccol.setCellValueFactory(new PropertyValueFactory<>("ec"));
    gtable.getColumns().add(geccol);
    TableColumn<Gene, String> gcognamecol = new TableColumn("Cog name");
    gcognamecol.setCellValueFactory(new PropertyValueFactory<>("cogname"));
    gtable.getColumns().add(gcognamecol);
    TableColumn<Gene, String> gcogcol = new TableColumn("Cog");
    gcogcol.setCellValueFactory(new PropertyValueFactory<>("cog"));
    gtable.getColumns().add(gcogcol);
    TableColumn<Gene, String> gcogannocol = new TableColumn("Cog annotation");
    gcogannocol.setCellValueFactory(new PropertyValueFactory<>("coganno"));
    gtable.getColumns().add(gcogannocol);
    TableColumn<Gene, String> gcogsymbcol = new TableColumn("Cog symbol");
    gcogsymbcol.setCellValueFactory(new PropertyValueFactory<>("cogsymbol"));
    gtable.getColumns().add(gcogsymbcol);
    TableColumn<Gene, String> gcazycol = new TableColumn("Cazy");
    gcazycol.setCellValueFactory(new PropertyValueFactory<>("cazy"));
    gtable.getColumns().add(gcazycol);
    TableColumn<Gene, String> gprescol = new TableColumn("Present in");
    gprescol.setCellValueFactory(new PropertyValueFactory<>("presentin"));
    gtable.getColumns().add(gprescol);

    TableColumn<Gene, Integer> ggroupindcol = new TableColumn("Group index");
    ggroupindcol.setCellValueFactory(new PropertyValueFactory<>("groupIndex"));
    gtable.getColumns().add(ggroupindcol);
    TableColumn<Gene, Integer> ggroupcovcol = new TableColumn("Group coverage");
    ggroupcovcol.setCellValueFactory(new PropertyValueFactory<>("groupCoverage"));
    gtable.getColumns().add(ggroupcovcol);
    TableColumn<Gene, Integer> ggroupsizecol = new TableColumn("Group size");
    ggroupsizecol.setCellValueFactory(new PropertyValueFactory<>("groupGeneCount"));
    gtable.getColumns().add(ggroupsizecol);

    TableColumn<Gene, String> glocprefcol = new TableColumn("Loc pref");
    glocprefcol.setCellValueFactory(new PropertyValueFactory<>("locpref"));
    gtable.getColumns().add(glocprefcol);
    TableColumn<Gene, String> gavgcpcol = new TableColumn("Avg GC%");
    gavgcpcol.setCellValueFactory(new PropertyValueFactory<>("avggcp"));
    gtable.getColumns().add(gavgcpcol);
    TableColumn<Gene, String> gnumloccol = new TableColumn("#Loc");
    gnumloccol.setCellValueFactory(new PropertyValueFactory<>("numloc"));
    gtable.getColumns().add(gnumloccol);
    TableColumn<Gene, String> gnumlocgroupcol = new TableColumn("#Loc group");
    gnumlocgroupcol.setCellValueFactory(new PropertyValueFactory<>("numlocgroup"));
    gtable.getColumns().add(gnumlocgroupcol);

    TableColumn<Gene, ShareNum> gsharenumcol = new TableColumn("Sharing number");
    gsharenumcol.setCellValueFactory(new PropertyValueFactory<>("sharingNumber"));
    gtable.getColumns().add(gsharenumcol);
    TableColumn<Gene, String> gmaxcyccol = new TableColumn("Max cyc");
    gmaxcyccol.setCellValueFactory(new PropertyValueFactory<>("maxCyc"));
    gtable.getColumns().add(gmaxcyccol);

    /*if( upper != null ) {
       SwingUtilities.invokeLater( new Runnable() {
    public void run() {
       //upper.setContent( botcomp );
       lower.setContent( topcomp );
    }
       });
    } else {
       splitpane.setBottomComponent(botcomp);
       splitpane.setTopComponent(topcomp);
    }
            
    groupModel = new TableModel() {
       @Override
       public int getRowCount() {
    return geneset.allgenegroups == null ? 0 : geneset.allgenegroups.size();
       }
            
       @Override
       public int getColumnCount() {
    return 32+geneset.specList.size();
       }
            
       @Override
       public String getColumnName(int columnIndex) {
    if (columnIndex == 0) {
       return "Desc";
    } else if (columnIndex == 1) {
       return "Origin";
    } else if (columnIndex == 2) {
       return "Genid";
    } else if (columnIndex == 3) {
       return "Refid";
    } else if (columnIndex == 4) {
       return "Unid";
    } else if (columnIndex == 5) {
       return "Keggid";
    } else if (columnIndex == 6) {
       return "Kegg pathway";
    } else if (columnIndex == 7) {
       return "KO";
    } else if (columnIndex == 8) {
       return "KSymbol";
    } else if (columnIndex == 9) {
       return "Symbol";
    } else if (columnIndex == 10) {
       return "KO name";
    } else if (columnIndex == 11) {
       return "Pdbid";
    } else if (columnIndex == 12) {
       return "EC";
    } else if (columnIndex == 13) {
       return "Cog name";
    } else if (columnIndex == 14) {
       return "Cog";
    } else if (columnIndex == 15) {
       return "Cog annotation";
    } else if (columnIndex == 16) {
       return "Cog symbol";
    } else if (columnIndex == 17) {
       return "Cazy";
    } else if (columnIndex == 18) {
       return "Present in";
    } else if (columnIndex == 19) {
       return "Group index";
    } else if (columnIndex == 20) {
       return "Group coverage";
    } else if (columnIndex == 21) {
       return "Group size";
    } else if (columnIndex == 22) {
       return "Locprev";
    } else if (columnIndex == 23) {
       return "Avg GC%";
    } else if (columnIndex == 24) {
       return "# of locus";
    } else if (columnIndex == 25) {
       return "# of loc in group";
    } else if (columnIndex == 26) {
       return "max length";
    } else if (columnIndex == 27) {
       return "sharing number";
    } else if (columnIndex == 28) {
       return "# Cyc";
    } else if (columnIndex == 29) {
       return "16S Corr";
    } else if (columnIndex == 30) {
       return "SingalP";
    } else if (columnIndex == 31) {
       return "TransM";
    } else {
       String spec = geneset.specList.get( columnIndex - 32 );
       if( spec != null ) {
          if( spec.toLowerCase().contains("thermus") ) {
             int i = spec.indexOf('_');
             return spec.substring(i+1, spec.length());
          } else return spec;
       }
       return "";
    }
    /* else if (columnIndex == 19) {
       return "T.tSG0";
    } else if (columnIndex == 20) {
       return "T.tJL18";
    } else if (columnIndex == 21) {
       return "T.tHB8";
    } else if (columnIndex == 22) {
       return "T.tHB27";
    } else if (columnIndex == 23) {
       return "T.scotoSA01";
    } else if (columnIndex == 24) {
       return "T.aqua";
    } else if (columnIndex == 25) {
       return "T.eggert";
    } else if (columnIndex == 26) {
       return "T.island";
    } else if (columnIndex == 27) {
       return "T.antan";
    } else if (columnIndex == 28) {
       return "T.scoto346";
    } else if (columnIndex == 29) {
       return "T.scoto1572";
    } else if (columnIndex == 30) {
       return "T.scoto252";
    } else if (columnIndex == 31) {
       return "T.scoto2101";
    } else if (columnIndex == 32) {
       return "T.scoto2127";
    } else if (columnIndex == 33) {
       return "T.scoto4063";
    } else if (columnIndex == 34) {
       return "T.oshimai";
    } else if (columnIndex == 35) {
       return "T.brockianus";
    } else if (columnIndex == 36) {
       return "T.filiformis";
    } else if (columnIndex == 37) {
       return "T.igniterrae";
    } else if (columnIndex == 38) {
       return "T.kawarayensis";
    } else if (columnIndex == 39) {
       return "T.arciformis";
    } else if (columnIndex == 40) {
       return "T.spCCB";
    } else if (columnIndex == 41) {
       return "T.spRLM";
    } else if (columnIndex == 42) {
       return "T.oshimaiJL2";
    } else if (columnIndex == 43) {
       return "MT.silvianus";
    } else if (columnIndex == 44) {
       return "MT.ruber";
    } else if (columnIndex == 45) {
       return "M.hydro";
    } else if (columnIndex == 46) {
       return "O.profu";
    }*
            
    //return "";
       }
            
       @Override
       public Class<?> getColumnClass(int columnIndex) {
    if( columnIndex == 19 || columnIndex == 20 || columnIndex == 28 )
       return Double.class;
    else if(columnIndex == 10 || (columnIndex >= 17 && columnIndex <= 28) )
       return Integer.class;
    else if (columnIndex >= 32)
       return Teg.class;
    return String.class;
       }
            
       @Override
       public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
       }
            
       @Override
       public Object getValueAt(int rowIndex, int columnIndex) {
    GeneGroup gg = geneset.allgenegroups.get(rowIndex);
    if (columnIndex == 0) {
       return gg.getCommonName();
    } else if (columnIndex == 1) {
       return gg.getCommonOrigin();
    } else if (columnIndex == 2) {
       return null;//gene.genid;
    } else if (columnIndex == 3) {
       return gg.getCommonRefId();
    } else if (columnIndex == 4) {
       return gg.getCommonUnId();
    } else if (columnIndex == 5) {
       return gg.getKeggid();
    } else if (columnIndex == 6) {
       return gg.getKeggPathway();
    } else if (columnIndex == 7) {
       return gg.getCommonKO();
    } else if (columnIndex == 8) {
       return gg.getCommonKSymbol();
    } else if (columnIndex == 9) {
       return gg.getCommonSymbol(); //ko2name != null ? ko2name.get( gg.getCommonKO() ) : null;
    } else if (columnIndex == 10) {
       String ret = geneset.ko2name != null ? geneset.ko2name.get( gg.getCommonKO() ) : null;
       if( ret == null ) {
          String symbol = gg.getCommonSymbol();
          if( symbol != null ) {
             if( symbol.length() <= 5 ) ret = symbol;
          }
       }
       return ret;
    } else if (columnIndex == 11) {
       return null;//gene.pdbid;
    } else if (columnIndex == 12) {
       return gg.getCommonEc();
    } else if (columnIndex == 13) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       if( cog != null ) {
          if( cog.name == null ) cog.name = geneset.cogidmap.get( cog.id );
          return cog.name;
       }
       return null;
    } else if (columnIndex == 14) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       return cog != null ? cog.id : null;
    } else if (columnIndex == 15) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       return cog != null ? cog.annotation : null;
    } else if (columnIndex == 16) {
       Cog cog = gg.getCommonCog( geneset.cogmap );
       return cog != null ? cog.genesymbol : null;
    } else if (columnIndex == 17) {
       return gg.getCommonCazy( geneset.cazymap );
    } else if (columnIndex == 18) {
       return gg.getSpecies().size();
    } else if (columnIndex == 19) {
       return gg.groupIndex;
    } else if (columnIndex == 20) {
       return gg.getGroupCoverage();
    } else if (columnIndex == 21) {
       return gg.getGroupGeneCount();
    } else if (columnIndex == 22) {
       return null;//gene.proximityGroupPreservation;
    } else if (columnIndex == 23) {
       return gg.getAvgGCPerc();
    } else if (columnIndex == 24) {
       return gg.genes.size();
    } else if (columnIndex == 25) {
       return gg.getGroupCount();
    } else if (columnIndex == 26) {
       return gg.getMaxLength();
    } else if (columnIndex == 27) {
       return geneset.specset.get( gg.getSpecies() );
    } else if (columnIndex == 28) {
       return gg.getMaxCyc();
    } else if (columnIndex == 29) {
       return gg.getGroupCoverage() == 39 && gg.getGroupCount() == 39 ? 0 : -1;
    } else if (columnIndex == 30) {
       return gg.getCommonSignalP();
    } else if (columnIndex == 31) {
       return gg.getCommonTransM();
    } else {
       String spec = geneset.specList.get( columnIndex - 32 );
       Teginfo ret = geneset.getGroupTes( gg, spec );
       return ret;
       //return null;
    }
    //return columnIndex >= 11 ? null : "";
       }
            
       @Override
       public void setValueAt(Object aValue, int rowIndex, int columnIndex) {}
            
       @Override
       public void addTableModelListener(TableModelListener l) {}
            
       @Override
       public void removeTableModelListener(TableModelListener l) {}
    };
    defaultModel = new TableModel() {
       @Override
       public int getRowCount() {
    int gs = geneset.genelist.size();
    return gs;
       }
            
       @Override
       public int getColumnCount() {
    return 26+geneset.specList.size();
       }
            
       @Override
       public String getColumnName(int columnIndex) {
    if (columnIndex == 0) {
       return "Desc";
    } else if (columnIndex == 1) {
       return "Origin";
    } else if (columnIndex == 2) {
       return "Genid";
    } else if (columnIndex == 3) {
       return "Refid";
    } else if (columnIndex == 4) {
       return "Unid";
    } else if (columnIndex == 5) {
       return "Keggid";
    } else if (columnIndex == 6) {
       return "KOid";
    } else if (columnIndex == 7) {
       return "KSymbol";
    } else if (columnIndex == 8) {
       return "Symbol";
    } else if (columnIndex == 9) {
       return "KOname";
    } else if (columnIndex == 10) {
       return "Pdbid";
    } else if (columnIndex == 11) {
       return "ecid";
    } else if (columnIndex == 12) {
       return "COG";
    } else if (columnIndex == 13) {
       return "COG name";
    } else if (columnIndex == 14) {
       return "Present in";
    } else if (columnIndex == 15) {
       return "Group index";
    } else if (columnIndex == 16) {
       return "Group coverage";
    } else if (columnIndex == 17) {
       return "Group size";
    } else if (columnIndex == 18) {
       return "Locprev";
    } else if (columnIndex == 19) {
       return "Avg GC%";
    } else if (columnIndex == 20) {
       return "# of locus";
    } else if (columnIndex == 21) {
       return "# of loc in group";
    } else if (columnIndex == 22) {
       return "max length";
    } else if (columnIndex == 23) {
       return "sharing number";
    } else if (columnIndex == 24) {
       return "# Cyc";
    } else if (columnIndex == 25) {
       return "16S Corr";
    } else {
       return geneset.specList.get( columnIndex - 26 );
    } /*else if (columnIndex == 19) {
       return "T.tSG0";
    } else if (columnIndex == 20) {
       return "T.tJL18";
    } else if (columnIndex == 21) {
       return "T.tHB8";
    } else if (columnIndex == 22) {
       return "T.tHB27";
    } else if (columnIndex == 23) {
       return "T.scotoSA01";
    } else if (columnIndex == 24) {
       return "T.aqua";
    } else if (columnIndex == 25) {
       return "T.eggert";
    } else if (columnIndex == 26) {
       return "T.island";
    } else if (columnIndex == 27) {
       return "T.antan";
    } else if (columnIndex == 28) {
       return "T.scoto346";
    } else if (columnIndex == 29) {
       return "T.scoto1572";
    } else if (columnIndex == 30) {
       return "T.scoto252";
    } else if (columnIndex == 31) {
       return "T.scoto2101";
    } else if (columnIndex == 32) {
       return "T.scoto2127";
    } else if (columnIndex == 33) {
       return "T.scoto4063";
    } else if (columnIndex == 34) {
       return "T.oshimai";
    } else if (columnIndex == 35) {
       return "T.brockianus";
    } else if (columnIndex == 36) {
       return "T.filiformis";
    } else if (columnIndex == 37) {
       return "T.igniterrae";
    } else if (columnIndex == 38) {
       return "T.kawarayensis";
    } else if (columnIndex == 39) {
       return "T.arciformis";
    } else if (columnIndex == 40) {
       return "T.spCCB";
    } else if (columnIndex == 41) {
       return "T.spRLM";
    } else if (columnIndex == 42) {
       return "T.oshimaiJL2";
    } else if (columnIndex == 43) {
       return "MT.silvianus";
    } else if (columnIndex == 44) {
       return "MT.ruber";
    } else if (columnIndex == 45) {
       return "M.hydro";
    } else if (columnIndex == 46) {
       return "O.profu";
    }*
       }
            
       @Override
       public Class<?> getColumnClass(int columnIndex) {
    if( columnIndex == 16 || columnIndex == 19 || columnIndex == 25 )
       return Double.class;
    else if(columnIndex >= 13 && columnIndex <= 24)
       return Integer.class;
    else if (columnIndex >= 26)
       return Teg.class;
    return String.class;
       }
            
       @Override
       public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
       }
            
       @Override
       public Object getValueAt(int rowIndex, int columnIndex) {
    Gene gene = geneset.genelist.get(rowIndex);
    if (columnIndex == 0) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gene.getGeneGroup().getCommonName() : null;
    } else if (columnIndex == 1) {
       return gene.getSpecies();
    } else if (columnIndex == 2) {
       return gene.genid;
    } else if (columnIndex == 3) {
       return gene.refid;
    } else if (columnIndex == 4) {
       return gene.uniid;
    } else if (columnIndex == 5) {
       return gene.keggid;
    } else if (columnIndex == 6) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonKO() : null;
    } else if (columnIndex == 7) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonKSymbol() : null;
    } else if (columnIndex == 8) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonSymbol() : null; //gene.symbol
    } else if (columnIndex == 9) {
       GeneGroup gg = gene.getGeneGroup();
       return gg != null ? gg.getCommonKOName( geneset.ko2name ) : null;
    } else if (columnIndex == 10) {
       return gene.pdbid;
    } else if (columnIndex == 11) {
       return gene.ecid;
    } else if (columnIndex == 12) {
       Cog cog = gene.getGeneGroup() != null ? gene.getGeneGroup().getCommonCog( geneset.cogmap ) : null;
       if( cog != null ) return cog.id;
       return null;
    } else if (columnIndex == 13) {
       Cog cog = gene.getGeneGroup() != null ? gene.getGeneGroup().getCommonCog( geneset.cogmap ) : null;
       if( cog != null ) return cog.name;
       return null;
    } else if (columnIndex == 14) {
       return gene.getGeneGroup().getSpecies().size();
    } else if (columnIndex == 15) {
       return gene.getGroupIndex();
    } else if (columnIndex == 16) {
       return gene.getGroupCoverage();
    } else if (columnIndex == 17) {
       return gene.getGroupGenCount();
    } else if (columnIndex == 18) {
       return gene.proximityGroupPreservation;
    } else if (columnIndex == 19) {
       return gene.getGCPerc();
    } else if (columnIndex == 20) {
       /*int val = 0;
       for (String str : gene.species.keySet()) {
          val += gene.species.get(str).tset.size();
       }*
       return 1;
    } else if (columnIndex == 21) {
       return gene.getGroupCount();
    } else if (columnIndex == 22) {
       return gene.getMaxLength();
    } else if (columnIndex == 23) {
       GeneGroup gg = gene.getGeneGroup();
       if( gg != null && gg.getSpecies() != null ) {
          return geneset.specset.get( gg.getSpecies() );
       }
       return null;
    } else if (columnIndex == 24) {
       gene.getMaxCyc();
    } else if (columnIndex == 25) {
       return gene.getGroupCoverage() == 35 && gene.getGroupCount() == 35 ? gene.corr16s : -1;
    } else {
       /*String spec = specList.get( columnIndex-26 );
       /*if( spec.contains("timidus") ) {
          System.err.println();
       }*
       //Teginfo set = gene.species.equals(spec) ? gene.teginfo : null;
       if( gene.getSpecies().equals( spec ) ) {
          return gene.tegeval;
       } else {
          return gene.getGeneGroup().species.get( spec );
       }*
               
       return null;
    }
    return columnIndex >= 17 ? null : "";
       }
            
       @Override
       public void setValueAt(Object aValue, int rowIndex, int columnIndex) {}
            
       @Override
       public void addTableModelListener(TableModelListener l) {}
            
       @Override
       public void removeTableModelListener(TableModelListener l) {}
    };
    table.setModel( groupModel );*/
    //table.setModel( defaultModel );

    /*
     * Comparator<Tegeval> wrapMe = new Comparator<Tegeval>() { public int
     * compare(Tegeval o1, Tegeval o2) { return o1.compareTo(o2); } };
     * DefaultRowSorter<TableModel, Integer> rowsorter =
     * (DefaultRowSorter<TableModel,Integer>)table.getRowSorter(); for( int
     * i = 10; i < 23; i++ ) { rowsorter.setComparator(i,
     * NullComparators.atEnd(wrapMe)); }
     */

    /*table.getRowSorter().addRowSorterListener( new RowSorterListener() {
       @Override
       public void sorterChanged(RowSorterEvent e) {
    for (String cstr : geneset.contigmap.keySet()) {
       Sequence c = geneset.contigmap.get(cstr);
       //c.count = 0;
       c.loc = 0.0;
    }
            
    if( table.getModel() == defaultModel ) {
       for (Gene g : geneset.genelist) {
          Tegeval tv = g.tegeval;
             // int first = tv.cont.indexOf('_');
             // int sec = tv.cont.indexOf('_',first+1);
          Sequence cont = tv.getContshort(); // tv.cont.substring(0,sec);
          if( cont != null && geneset.contigmap.containsKey(cont.getName()) ) {
             Sequence c = geneset.contigmap.get(cont.getName());
             //c.count++;
             int val = table.convertRowIndexToView(g.index);
             c.loc += (double) val;
          }
       }
    }
    for( JSplitPane gsplitpane : splitpaneList ) {
       gsplitpane.repaint();
    }
       }
    });*/

    ftable = upper;
    ftable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    /*ftable = new JTable() {
       public String getToolTipText(MouseEvent me) {
    Point p = me.getPoint();
    int r = rowAtPoint(p);
    int c = columnAtPoint(p);
    if (r >= 0 && r < super.getRowCount()) {
       Object ret = super.getValueAt(r, c);
       if (ret != null) {
          return ret.toString(); // super.getToolTipText( me );
       }
    }
    return "";
       }
    };*/

    ContextMenu fpopup = new ContextMenu();
    MenuItem amigo = new MenuItem("Amigo lookup");
    amigo.setOnAction(e -> {
        String go = ftable.getSelectionModel().getSelectedItem().getGo();
        try {
            // GeneSetHead.this.getAppletContext().
            Desktop.getDesktop()
                    .browse(new URI("http://amigo.geneontology.org/cgi-bin/amigo/term_details?term=" + go));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(amigo);
    MenuItem keggl = new MenuItem("KEGG lookup");
    keggl.setOnAction(e -> {
        String kegg = ftable.getSelectionModel().getSelectedItem().getKegg();
        try {
            Desktop.getDesktop().browse(new URI("http://www.genome.jp/dbget-bin/www_bget?rn:" + kegg));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(keggl);
    MenuItem ecl = new MenuItem("EC lookup");
    ecl.setOnAction(e -> {
        String ec = ftable.getSelectionModel().getSelectedItem().getEc();
        try {
            Desktop.getDesktop().browse(new URI("http://enzyme.expasy.org/EC/" + ec));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(ecl);
    fpopup.getItems().add(new SeparatorMenuItem());

    MenuItem excelreport = new MenuItem("Excel report");
    excelreport.setOnAction(e -> {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("enzyme");
        int k = 0;
        for (Function f : ftable.getSelectionModel().getSelectedItems()) {
            //String ec = (String)ftable.getValueAt(r, 1);
            //String go = (String)ftable.getValueAt(r, 0);

            //int i = ftable.getSelectionModel().convertRowIndexToModel(r);
            //Function f = geneset.funclist.get(i);
            for (GeneGroup gg : f.getGeneGroups()) {
                for (String spec : gg.getSpecies()) {
                    Teginfo ti = gg.getGenes(spec);

                    Row row = sheet.createRow(k++);
                    Cell ecell = row.createCell(0);
                    ecell.setCellValue("EC:" + f.getEc());
                    Cell ncell = row.createCell(1);
                    ncell.setCellValue(f.getName());
                    Cell spell = row.createCell(2);
                    spell.setCellValue(spec);
                    Cell seqcell = row.createCell(3);
                    seqcell.setCellValue(ti.tset.size());
                }
                /*for( Gene g :gg.genes ) {
                   Row    row = sheet.createRow(k++);
                   Cell    ecell = row.createCell(0);
                   ecell.setCellValue( "EC:"+f.ec );
                   Cell    ncell = row.createCell(1);
                   ncell.setCellValue( f.name );
                   Cell    spell = row.createCell(2);
                   spell.setCellValue( g.getSpecies() );
                   Cell    seqcell = row.createCell(3);
                   seqcell.setCellValue( g.tegeval.getAlignedSequence().toString() );
                }*/
            }
            sheet.createRow(k++);
        }

        try {
            Path tempfile = Files.createTempFile("enzyme", ".xlsx");
            OutputStream os = Files.newOutputStream(tempfile);
            workbook.write(os);
            os.close();

            Desktop.getDesktop().open(tempfile.toFile());
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    fpopup.getItems().add(excelreport);
    ftable.setContextMenu(fpopup);

    ContextMenu popup = new ContextMenu();
    MenuItem splitaction = new MenuItem("Split");
    splitaction.setOnAction(e -> {
        Dialog<Set<GeneGroup>> dialog = new Dialog<>();
        dialog.setResizable(true);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 20, 10, 10));

        TextField len = new TextField();
        len.setPromptText("0.5");
        TextField id = new TextField();
        id.setPromptText("0.5");

        grid.add(new Label("%Length:"), 0, 0);
        grid.add(len, 1, 0);
        grid.add(new Label("%Identity:"), 0, 1);
        grid.add(id, 1, 1);

        final ListView<GeneGroup> list = new ListView<>();
        list.setPrefWidth(400);
        grid.add(list, 0, 2, 2, 1);

        final GeneGroup gg = table.getSelectionModel().getSelectedItem();
        list.setItems(FXCollections.singletonObservableList(gg));

        Label groupsize = new Label("" + gg.genes.size());
        grid.add(groupsize, 0, 3, 2, 1);

        len.textProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue.equals(oldValue)) {
                double d = 0;
                try {
                    d = Double.parseDouble(newValue);
                } catch (Exception ex) {
                }

                if (d > 0) {
                    Set<GeneGroup> ggmap = new HashSet<>();
                    Map<String, Integer> blosumMap = JavaFasta.getBlosumMap(false);
                    for (Gene gene : gg.genes) {
                        if (ggmap.stream().flatMap(f -> f.genes.stream()).noneMatch(p -> gene == p)) {
                            Set<Gene> ggset = new HashSet<>();
                            Sequence seq1 = gene.tegeval.getAlignedSequence();
                            for (Gene cgene : gg.genes) {
                                Sequence seq2 = cgene.tegeval.getAlignedSequence();
                                int[] tscore = GeneCompare.blosumValue(seq1, seq1, seq2, blosumMap);
                                int sscore = GeneCompare.blosumValue(seq1, seq2, blosumMap);

                                double dval = (double) (sscore - tscore[1]) / (double) (tscore[0] - tscore[1]);
                                if (dval > d) {
                                    ggset.add(cgene);
                                }
                            }
                            System.err.println(ggset.size());

                            Set<GeneGroup> osubgg = ggmap.stream().filter(f -> {
                                Set<Gene> gs = new HashSet<>(ggset);
                                gs.retainAll(f.genes);
                                return gs.size() > 0;
                            }).collect(Collectors.toSet());
                            GeneGroup subgg;
                            if (osubgg.size() > 0) {
                                Iterator<GeneGroup> git = osubgg.iterator();
                                subgg = git.next();
                                while (git.hasNext()) {
                                    GeneGroup remgg = git.next();
                                    subgg.addGenes(remgg.genes);
                                    ggmap.remove(remgg);
                                }
                            } else {
                                subgg = new GeneGroup();
                                subgg.setCogMap(gg.getCogMap());
                                subgg.setKonameMap(gg.getKonameMap());
                                subgg.setSpecSet(gg.getSpecSet());
                                ggmap.add(subgg);
                            }
                            subgg.addGenes(ggset);
                        }
                    }
                    Set<GeneGroup> sgg = ggmap.stream().collect(Collectors.toSet());

                    List<GeneGroup> lgg = new ArrayList(sgg);
                    list.setItems(FXCollections.observableList(lgg));
                    dialog.setResultConverter(param -> sgg);
                }
            }
        });

        dialog.getDialogPane().setContent(grid);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
        dialog.getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
        Optional<Set<GeneGroup>> ogg = dialog.showAndWait();

        ogg.ifPresent(c -> {
            geneset.allgenegroups.remove(gg);
            geneset.allgenegroups.addAll(c);

            Map<String, String> env = new HashMap<>();
            env.put("create", "true");
            try {
                geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
                for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                    Files.walk(root).filter(f -> f.toString().startsWith("/aligned"))
                            .filter(f -> f.toString().endsWith(".aa")).filter(f -> {
                                String filename = f.getFileName().toString();
                                return gg.genes.stream().anyMatch(g -> {
                                    String fnid = filename.substring(0, filename.length() - 3);
                                    return g.name.equals(fnid);
                                });
                            }).forEach(p -> {
                                try {
                                    Files.deleteIfExists(p);
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }
                            });
                    /*for( Gene g : gg.genes ) {
                       if( g.keggpathway != null ) {
                          String sub = g.keggpathway.substring(0,3);
                          Path subf = root.resolve(sub);
                          if( Files.exists(subf) ) {
                             String[] split = g.keggpathway.split(" ");
                             for( String s : split ) {
                      Path pimg = subf.resolve(s+".png");
                      if( Files.exists(pimg) ) {
                         showKeggPathway( sub, pimg );
                      }
                             }
                          }
                       }
                    }*/
                    final Path p = root.resolve("/aligned");
                    c.stream().forEach(fgg -> {
                        Path np = p.resolve(fgg.genes.iterator().next().getName());
                        try {
                            Writer w = Files.newBufferedWriter(np);
                            fgg.getFasta(w, false);
                            w.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    });
                    break;
                }
                geneset.zipfilesystem.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
    });
    popup.getItems().add(splitaction);
    MenuItem joinaction = new MenuItem("Join");

    popup.getItems().add(joinaction);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showkegg = new MenuItem("Show KEGG pathway");
    showkegg.setOnAction(e -> {
        GeneGroup gg = table.getSelectionModel().getSelectedItem();

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

        /*String uristr = "jar:" + geneset.zippath.toUri();
        URI zipuri = URI.create( uristr /*.replace("file://", "file:")* );
        final List<Path>   lbi = new ArrayList<>();*/
        boolean shown = false;
        try {
            geneset.zipfilesystem = FileSystems.newFileSystem(geneset.zipuri, env);
            for (Path root : geneset.zipfilesystem.getRootDirectories()) {
                for (Gene g : gg.genes) {
                    if (g.keggpathway != null) {
                        String sub = g.keggpathway.substring(0, 3);
                        Path subf = root.resolve(sub);
                        if (Files.exists(subf)) {
                            String[] split = g.keggpathway.split(" ");
                            for (String s : split) {
                                Path pimg = subf.resolve(s + ".png");
                                if (Files.exists(pimg)) {
                                    showKeggPathway(sub, pimg);
                                    shown = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                break;
            }
            geneset.zipfilesystem.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (!shown) {
            for (Gene g : gg.genes) {
                if (g.keggpathway != null) {
                    String[] keggsplit = g.keggpathway.split(";");
                    Arrays.stream(keggsplit).map(s -> s.split(":")[0]).findFirst().ifPresent(c -> {
                        try {
                            Desktop.getDesktop().browse(
                                    URI.create("http://www.genome.jp/dbget-bin/www_bget?map" + c.substring(2)));
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    });
                }
            }
        }
    });
    popup.getItems().add(showkegg);
    MenuItem plasmid = new MenuItem("Plasmid");
    plasmid.setOnAction(e -> {
        Gene g = gtable.getSelectionModel().getSelectedItem();
        Sequence contig = g.tegeval.getContshort();
        String contigstr = contig.toString();
        contig.plasmid = !geneset.plasmids.contains(contigstr);
        if (contig.plasmid)
            geneset.plasmids.add(contigstr);
        else
            geneset.plasmids.remove(contigstr);

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

            //fs = FileSystems.newFileSystem( uri, env );
            //FileSystem fs = FileSystems.newFileSystem(uri, env);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (String contigname : geneset.plasmids) {
                baos.write((contigname + "\n").getBytes());
            }

            Path nf = geneset.zipfilesystem.getPath("/plasmids.txt");
            long bl = Files.copy(new ByteArrayInputStream(baos.toByteArray()), nf,
                    StandardCopyOption.REPLACE_EXISTING);
            //System.err.println( "eeerm " + bl );
            geneset.zipfilesystem.close();

            /*Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
            for( String phage : phageset ) {
               writer.write( phage + "\n" );
            }
            writer.close();*/

            //writer.write("hello");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(plasmid);
    MenuItem designate = new MenuItem("Designate");
    designate.setOnAction(e -> {
        SwingUtilities.invokeLater(() -> {
            JComboBox<String> descombo = new JComboBox<>(
                    geneset.deset.toArray(new String[geneset.deset.size()]));
            descombo.setEditable(true);
            JOptionPane.showMessageDialog(GeneSetHead.this, descombo);
            String val = descombo.getSelectedItem().toString();
            geneset.deset.add(val);
            for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                g.tegeval.designation = val;
                if (g.id != null) {
                    geneset.designations.put(g.id, val);
                } else {
                    System.err.println(g.refid);
                }
                //ta.append( g.tegeval.id + "\n" );
            }

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

                //fs = FileSystems.newFileSystem( uri, env );
                //FileSystem fs = FileSystems.newFileSystem(uri, env);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                for (String geneid : geneset.designations.keySet()) {
                    String design = geneset.designations.get(geneid);
                    baos.write((geneid + "\t" + design + "\n").getBytes());
                }

                Path nf = geneset.zipfilesystem.getPath("/designations.txt");
                long bl = Files.copy(new ByteArrayInputStream(baos.toByteArray()), nf,
                        StandardCopyOption.REPLACE_EXISTING);
                //System.err.println( "eeerm " + bl );
                geneset.zipfilesystem.close();

                /*Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE);
                for( String phage : phageset ) {
                    writer.write( phage + "\n" );
                }
                writer.close();*/

                //writer.write("hello");
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            /*JFrame frame = new JFrame("Ids");
            frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
            frame.setSize(800, 600);
            JTextArea   ta = new JTextArea();
            JScrollPane sp = new JScrollPane( ta );
            frame.add( sp );
                    
            frame.setVisible( true );*/
        });
    });
    popup.getItems().add(designate);
    MenuItem koname = new MenuItem("KO to name");
    koname.setOnAction(e -> {
        Set<String> koids = new HashSet<>();
        for (Gene g : geneset.genelist) {
            if (g.koid != null && g.koid.length() > 0
                    && !(geneset.ko2name != null && geneset.ko2name.containsKey(g.koid)))
                koids.add(g.koid);
        }

        try {
            Map<String, String> ko2name = new HashMap<>();
            int cnt = 0;
            for (String koid : koids) {
                URL url = new URL("http://www.kegg.jp/dbget-bin/www_bget?ko:" + koid);
                InputStream is0 = url.openStream();
                StringBuilder sb = new StringBuilder();
                BufferedReader br0 = new BufferedReader(new InputStreamReader(is0));
                String line0 = br0.readLine();
                while (line0 != null) {
                    sb.append(line0);
                    line0 = br0.readLine();
                }
                br0.close();

                int i = sb.indexOf("<nobr>Name</nobr>");
                if (i != -1) {
                    int k = sb.indexOf(":hidden\">");
                    if (k != -1) {
                        k = sb.indexOf(":hidden\">", k + 9);
                        if (k != -1) {
                            String koname0 = sb.substring(k + 9, sb.indexOf("<br>", k));
                            ko2name.put(koid, koname0);

                            System.err.println(koid + "\t" + koname0);
                        }
                    }
                }

                System.err.println(ko2name.size() + " " + koids.size());
                //if( cnt++ > 20 ) break;
            }

            FileWriter fw = new FileWriter("~ko2name.txt");
            for (String koid : ko2name.keySet()) {
                fw.write(koid + "\t" + ko2name.get(koid) + "\n");
            }
            fw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(koname);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem genegainloss = new MenuItem("Gene gain/loss");
    genegainloss.setOnAction(e -> {
        Map<Node, List<GeneGroup>> nodeGainMap = new HashMap<>();
        Map<Node, List<GeneGroup>> nodeLossMap = new HashMap<>();

        /*String treestr = "";
        JFileChooser fc = new JFileChooser();
        if( fc.showOpenDialog( applet ) == JFileChooser.APPROVE_OPTION ) {
           File file = fc.getSelectedFile();
           try {
              byte[] bb = Files.readAllBytes( Paths.get(file.toURI()) );
              treestr = new String( bb );
           } catch (IOException e1) {
              e1.printStackTrace();
           }
        }*/

        Serifier serifier = getConcatenatedSequences(false, true);
        String tree = serifier.getFastTree(serifier.lseq, geneset.user, false);

        TreeUtil tu = new TreeUtil();
        Node n = tu.parseTreeRecursive(tree, false);

        TableModel model = new TableModel() {
            @Override
            public int getRowCount() {
                return geneset.getSpecies().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.getSpecies().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);
        FlowLayout flowlayout = new FlowLayout();
        JComponent c = new JComponent() {
        };
        c.setLayout(flowlayout);
        c.add(scroll);
        JOptionPane.showMessageDialog(comp, c);

        List<String> rootgroup = new ArrayList<>();
        int[] rr = table.getSelectedRows();
        for (int r : rr) {
            rootgroup.add((String) table.getValueAt(r, 0));
        }

        //String[] sobj = {"mt.ruber", "mt.silvanus", "o.profundus", "m.hydrothermalis"};
        Node newnode = tu.getParent(n, new HashSet<>(rootgroup));
        tu.rerootRecur(n, newnode);

        File f = new File("/home/sigmar/gain_list.txt");
        try {
            PrintStream ps = new PrintStream(f);
            geneset.assignGain(newnode, nodeGainMap, ps);
            ps.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        f = new File("/home/sigmar/loss_list.txt");
        try {
            PrintStream ps = new PrintStream(f);
            geneset.assignLoss(newnode, nodeLossMap, ps);
            ps.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(genegainloss);
    MenuItem concattree = new MenuItem("Concatenate tree");
    concattree.setOnAction(e -> {
        Serifier serifier = getConcatenatedSequences(false, true);

        boolean succ = true;
        if (comp instanceof Applet) {
            try {
                JSObject win = JSObject.getWindow((Applet) comp);
                StringWriter sw = new StringWriter();
                serifier.writeFasta(serifier.lseq, sw, null);
                sw.close();
                win.call("fasttree", new Object[] { sw.toString() });
            } catch (NoSuchMethodError | Exception e1) {
                e1.printStackTrace();
                succ = false;
            }
        }

        /*if( !succ ) {
           String             tree = serifier.getFastTree();
           if( cs.connections().size() > 0 ) {
        cs.sendToAll( tree );
            } else if( Desktop.isDesktopSupported() ) {
        cs.message = tree;
        //String uristr = "http://webconnectron.appspot.com/Treedraw.html?tree="+URLEncoder.encode( tree, "UTF-8" );
        String uristr = "http://webconnectron.appspot.com/Treedraw.html?ws=127.0.0.1:8887";
              try {
          Desktop.getDesktop().browse( new URI(uristr) );
              } catch (IOException | URISyntaxException e1) {
          e1.printStackTrace();
              }
            }
           System.err.println( tree );
        }*/
        showAlignedSequences(comp, serifier);
    });
    popup.getItems().add(concattree);
    MenuItem majocons = new MenuItem("Majority rule consensus");
    majocons.setOnAction(e -> {
        Serifier serifier = new Serifier();

        Set<GeneGroup> genegroups = new HashSet<GeneGroup>();
        if (!isGeneview()) {
            genegroups.addAll(table.getSelectionModel().getSelectedItems());
        } else {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                genegroups.add(gg.getGeneGroup());
            }
        }

        TreeUtil treeutil = new TreeUtil();
        Map<Set<String>, NodeSet> nmap = new HashMap<Set<String>, NodeSet>();
        for (GeneGroup ggroup : genegroups) {
            //List<Sequence>   seqlist = new ArrayList<Sequence>();

            for (Tegeval tv : ggroup.getTegevals()) {
                String spec = tv.getContshort().getSpec();
                Sequence seq = tv.getAlignedSequence();

                //Sequence seq = new Sequence( spec, null );
                //if( seqstr != null && seqstr.length() > 0 ) seq.append( seqstr );
                serifier.addSequence(seq);
            }

            String tree = serifier.getFastTree(serifier.lseq, geneset.user, false);
            Node n = treeutil.parseTreeRecursive(tree, false);
            treeutil.setLoc(0);
            n.nodeCalcMap(nmap);
        }

        Node guidetree = null;

        /*********************************** Serifier serifier = getConcatenatedSequences();
        String tree = serifier.getFastTree();
        guidetree = treeutil.parseTreeRecursive( tree, false );*/

        Node root = DataTable.majoRuleConsensus(treeutil, nmap, guidetree, false);
        String tree = root.toString();

        if (geneset.cs.connections().size() > 0) {
            geneset.cs.sendToAll(tree);
        } else if (Desktop.isDesktopSupported()) {
            geneset.cs.message = tree;
            //String uristr = "http://webconnectron.appspot.com/Treedraw.html?tree="+URLEncoder.encode( tree, "UTF-8" );
            String uristr = "http://webconnectron.appspot.com/Treedraw.html?ws=127.0.0.1:8887";
            try {
                Desktop.getDesktop().browse(new URI(uristr));
            } catch (IOException | URISyntaxException e1) {
                e1.printStackTrace();
            }
        }
    });
    popup.getItems().add(majocons);
    MenuItem addsim = new MenuItem("Add similar");
    addsim.setOnAction(e -> {
        /*int r = table.getSelectedRow();
        int c = table.getSelectedColumn();
                
        Object o = table.getValueAt(r, c);
                
        if (c >= 18) {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (no != null && !table.isRowSelected(i))
          table.addRowSelectionInterval(i, i);
           }
        } else {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (o.equals(no) && !table.isRowSelected(i))
          table.addRowSelectionInterval(i, i);
           }
        }*/
    });
    popup.getItems().add(addsim);
    MenuItem selsim = new MenuItem("Select similar");
    selsim.setOnAction(e -> {
        /*int r = table.getSelectedRow();
        int c = table.getSelectedColumn();
                
        Object o = table.getValueAt(r, c);
                
        table.removeRowSelectionInterval(0, table.getRowCount() - 1);
        if (c >= 18) {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (no != null)
          table.addRowSelectionInterval(i, i);
           }
        } else {
           for (int i = 0; i < table.getRowCount(); i++) {
              Object no = table.getValueAt(i, c);
              if (o.equals(no))
          table.addRowSelectionInterval(i, i);
           }
        }*/
    });
    popup.getItems().add(selsim);
    MenuItem tabtxt = new MenuItem("Table text");
    tabtxt.setOnAction(e -> {
        /*JTextArea ta = new JTextArea();
        ta.setDragEnabled(true);
        JScrollPane scrollpane = new JScrollPane(ta);
                
        StringBuilder sb = new StringBuilder();
        int[] rr = table.getSelectedRows();
        for (int r : rr) {
           for (int c = 0; c < table.getColumnCount() - 1; c++) {
              Object o = table.getValueAt(r, c);
              if (c > 18) {
          if (o != null) {
             String val = o.toString();
             int k = val.indexOf(' ');
             sb.append(val.substring(0, k));
             sb.append("\t" + val.substring(k + 1));
          } else
             sb.append("\t");
              } else {
          if (o != null) {
             sb.append(o.toString());
          }
              }
              sb.append("\t");
           }
           Object o = table.getValueAt(r, table.getColumnCount() - 1);
           if (o != null) {
              String val = o.toString();
              int k = val.indexOf(' ');
              sb.append(val.substring(0, k));
              sb.append("\t" + val.substring(k + 1));
           } else
              sb.append("\t");
           sb.append("\n");
        }
                
        ta.setText(sb.toString());
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);*/
    });
    popup.getItems().add(tabtxt);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem ncbil = new MenuItem("NCBI lookup");
    ncbil.setOnAction(e -> {
        /*int r = table.getSelectedRow();
        if (r >= 0) {
           String ref = (String) table.getValueAt(r, 2);
           try {
              Desktop.getDesktop().browse(new URI("http://www.ncbi.nlm.nih.gov/gene?term=" + ref));
           } catch (IOException e1) {
              e1.printStackTrace();
           } catch (URISyntaxException e1) {
              e1.printStackTrace();
           }
        }*/
    });
    popup.getItems().add(ncbil);
    table.setContextMenu(popup);
    gtable.setContextMenu(popup);

    TableColumn<Function, String> gocol = new TableColumn("GO");
    gocol.setCellValueFactory(new PropertyValueFactory<>("go"));
    ftable.getColumns().add(gocol);
    TableColumn<Function, String> ecfcol = new TableColumn("EC");
    ecfcol.setCellValueFactory(new PropertyValueFactory<>("ec"));
    ftable.getColumns().add(ecfcol);
    TableColumn<Function, String> metacyccol = new TableColumn("MetaCyc");
    metacyccol.setCellValueFactory(new PropertyValueFactory<>("metacyc"));
    ftable.getColumns().add(metacyccol);
    TableColumn<Function, String> keggcol = new TableColumn("KEGG");
    keggcol.setCellValueFactory(new PropertyValueFactory<>("kegg"));
    ftable.getColumns().add(keggcol);
    TableColumn<Function, String> funcovcol = new TableColumn("Funciton coverage");
    funcovcol.setCellValueFactory(new PropertyValueFactory<>("speciesCount"));
    ftable.getColumns().add(funcovcol);
    TableColumn<Function, String> numprotcol = new TableColumn("Number of proteins");
    numprotcol.setCellValueFactory(new PropertyValueFactory<>("groupCount"));
    ftable.getColumns().add(numprotcol);

    TableColumn<Function, String> namecol = new TableColumn("Name");
    namecol.setCellValueFactory(new PropertyValueFactory<>("name"));
    ftable.getColumns().add(namecol);
    TableColumn<Function, String> namespacecol = new TableColumn("Namespace");
    namespacecol.setCellValueFactory(new PropertyValueFactory<>("namespace"));
    ftable.getColumns().add(namespacecol);
    TableColumn<Function, String> desccol = new TableColumn("Desc");
    desccol.setCellValueFactory(new PropertyValueFactory<>("desc"));
    ftable.getColumns().add(desccol);

    ftable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    //ftable.setAutoCreateRowSorter(true);
    /*ftablemodel = new TableModel() {
       @Override
       public int getRowCount() {
    return geneset.funclist.size();
       }
            
       @Override
       public int getColumnCount() {
    return 9;
       }
            
       @Override
       public String getColumnName(int columnIndex) {
    if (columnIndex == 0)
       return "GO";
    else if (columnIndex == 1)
       return "EC";
    else if (columnIndex == 2)
       return "MetaCyc";
    else if (columnIndex == 3)
       return "KEGG";
    else if (columnIndex == 4)
       return "Function coverage";
    else if (columnIndex == 5)
       return "Number of proteins";
    else if (columnIndex == 6)
       return "Name";
    else if (columnIndex == 7)
       return "Namespace";
    else if (columnIndex == 8)
       return "Def";
    return "";
       }
            
       @Override
       public Class<?> getColumnClass(int columnIndex) {
    if( columnIndex == 4 || columnIndex == 5 )
       return Integer.class;
    return String.class;
       }
            
       @Override
       public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
       }
            
       @Override
       public Object getValueAt(int rowIndex, int columnIndex) {
    Function func = geneset.funclist.get(rowIndex);
    if( columnIndex == 0 )
       return func.go;
    else if( columnIndex == 1 )
       return func.ec;
    else if( columnIndex == 2 )
       return func.metacyc;
    else if( columnIndex == 3 )
       return func.kegg;
    else if( columnIndex == 4 )
       return func.getSpeciesCount();
    else if( columnIndex == 5 )
       return table.getModel() == groupModel ? func.getGroupSize() : func.getGeneCount();
    else if( columnIndex == 6 )
       return func.name;
    else if( columnIndex == 7 )
       return func.namespace;
    else if( columnIndex == 8 )
       return func.desc;
    return null;
       }
            
       @Override
       public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
       }
            
       @Override
       public void addTableModelListener(TableModelListener l) {
       }
            
       @Override
       public void removeTableModelListener(TableModelListener l) {
       }
    };
    ftable.setModel( ftablemodel );
    fscrollpane.setViewportView(ftable);*/

    updateFilter(ftable, null);
    updateFilter(table, label);

    combo.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        String sel = newValue;
        filterset.clear();
        if (geneset.pathwaymap.containsKey(sel)) {
            Set<String> enz = geneset.pathwaymap.get(sel);
            for (Function f : geneset.funclist) {
                if (f.getEc() != null && enz.contains(f.getEc())) {
                    filterset.add(f.index);
                }
            }
        }
        updateFilter(ftable, null);
    });

    specombo.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        String sel = newValue;
        genefilterset.clear();
        for (Gene g : geneset.genelist) {
            Tegeval tv = g.tegeval;
            if (sel.equals(tv.teg)) {
                //System.out.println(g.name + " " + sp + " " + sel + "  " + tv.eval);
                genefilterset.add(g.index);
            }
        }
        updateFilter(table, label);
    });

    MenuItem findcon = new MenuItem("Find conserved terms");
    findcon.setOnAction(e -> {
        Set<Integer> res = new HashSet<>();
        for (Function f : geneset.funclist) {
            if (f.getGeneGroups() != null) {
                Set<String> check = new HashSet<>();
                for (GeneGroup g : f.getGeneGroups()) {
                    //Gene g = genemap.get(str);
                    if (g.species != null) {
                        if (check.isEmpty())
                            check.addAll(g.species.keySet());
                        else if (!(check.size() == g.species.size() && check.containsAll(g.species.keySet()))) {
                            check.clear();
                            break;
                        }
                    }
                }
                if (!check.isEmpty())
                    res.add(f.index);
            }
        }
        filterset.clear();
        for (int i : res) {
            filterset.add(i);
        }
        updateFilter(ftable, null);
    });
    fpopup.getItems().add(findcon);
    fpopup.getItems().add(new SeparatorMenuItem());

    MenuItem showgen = new MenuItem("Show genes");
    showgen.setOnAction(e -> {
        genefilterset.clear();
        Set<GeneGroup> sset = new HashSet<>();
        for (Function f : (ObservableList<Function>) ftable.getSelectionModel().getSelectedItems()) {
            if (!isGeneview()) {
                sset.addAll(f.getGeneGroups());
                /*if( sset != null ) for (GeneGroup gg : sset) {
                   //Gene g = genemap.get(s);
                   genefilterset.add(gg.index);
                }*/
            } else {
                /*Set<Gene> sset = f.getGeneentries();
                for (Gene g : sset) {
                   //Gene g = genemap.get(s);
                   genefilterset.add(g.index);
                }*/
            }
        }

        //int[] rows = sset.stream().mapToInt( gg -> sortedData.indexOf(gg) ).toArray();
        //table.getSelectionModel().selectIndices(rows[0], rows);

        filteredData.setPredicate(genegroup -> {
            return sset.contains(genegroup);
        });
        if (label != null)
            label.setText(
                    table.getItems().size() + "/" + table.getSelectionModel().getSelectedIndices().size());
    });
    fpopup.getItems().add(showgen);

    table.getSelectionModel().selectedItemProperty().addListener(e -> {
        // table.clearSelection();
        tableisselecting = true;
        if (!ftableisselecting && filterset.isEmpty()) {
            //ftable.removeRowSelectionInterval(0, ftable.getRowCount() - 1);
            if (!isGeneview()) {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    for (Function f : gg.getFunctions()) {
                        try {
                            ftable.getSelectionModel().select(f);
                            //int rf = ftable.convertRowIndexToView(f.index);
                            //if( rf >= 0 && rf < ftable.getRowCount() ) ftable.addRowSelectionInterval(rf, rf);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            } else {
                for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                    if (g.funcentries != null) {
                        for (Function f : g.funcentries) {
                            //Function f = funcmap.get(go);
                            try {
                                ftable.getSelectionModel().select(f);
                                //int rf = ftable.convertRowIndexToView(f.index);
                                //if( rf >= 0 && rf < ftable.getRowCount() ) ftable.addRowSelectionInterval(rf, rf);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        tableisselecting = false;
    });

    ftable.setOnKeyPressed(ke -> {
        if (ke.getCode() == KeyCode.ESCAPE) {
            ffilteredData.setPredicate(null);
        }
    });

    table.setOnKeyPressed(ke -> {
        if (ke.getCode() == KeyCode.ESCAPE) {
            GeneGroup selgg = table.getSelectionModel().getSelectedItem();

            List<GeneGroup> sel = new ArrayList<>(filteredData);
            filteredData.setPredicate(null);
            int[] rows = sel.stream().mapToInt(gg -> sortedData.indexOf(gg)).toArray();
            if (rows.length > 0)
                table.getSelectionModel().selectIndices(rows[0], rows);
            if (label != null)
                label.setText(
                        table.getItems().size() + "/" + table.getSelectionModel().getSelectedIndices().size());

            table.scrollTo(selgg);
            //genefilterset.clear();
            //updateFilter(table, genefilter, label);
            //geneset.scrollToSelection( table );
        }
    });

    table.setOnMousePressed(e -> {
        tableisselecting = true;
        if (!ftableisselecting && e.getClickCount() == 2) {
            /*
             * int[] rr = ftable.getSelectedRows(); int minr =
             * ftable.getRowCount(); int maxr = 0; for( int r : rr ) {
             * if( r < minr ) minr = r; if( r > maxr ) maxr = r; }
             * ftable.removeRowSelectionInterval(minr, maxr);
             */
            // ftable.removeRowSelectionInterval(0, filterset.isEmpty()
            // ? ftable.getRowCount()-1 : filterset.size()-1 );

            Set<Function> fset = new HashSet<>();
            filterset.clear();
            if (!isGeneview()) {
                for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                    fset.addAll(gg.getFunctions());
                }
            } else {
                for (Gene g : gtable.getSelectionModel().getSelectedItems()) {
                    if (g.funcentries != null) {
                        for (Function f : g.funcentries) {
                            //Function f = funcmap.get(go);
                            // ftable.getRowSorter().convertRowIndexToView(index)
                            // int rf = ftable.convertRowIndexToView(
                            // f.index );
                            filterset.add(f.index);
                            // ftable.addRowSelectionInterval(rf, rf);
                        }
                    }
                }
            }
            ffilteredData.setPredicate(p -> fset.contains(p));
        }
        tableisselecting = false;
    });

    ftable.setOnMousePressed(e -> {
        ftableisselecting = true;
        Set<GeneGroup> ggset = new HashSet<>();
        if (!tableisselecting && e.getClickCount() == 2) {
            genefilterset.clear();
            for (Function f : (ObservableList<Function>) ftable.getSelectionModel().getSelectedItems()) {
                if (f.getGeneentries() != null) {
                    if (!isGeneview()) {
                        ggset.addAll(f.getGeneGroups());
                    } else {
                        for (Gene g : f.getGeneentries()) {
                            //Gene g = genemap.get(ref);
                            // int rf = table.convertRowIndexToView( g.index
                            // );
                            // table.addRowSelectionInterval(rf, rf);
                            genefilterset.add(g.index);
                        }
                    }
                }
            }
            filteredData.setPredicate(p -> ggset.contains(p));
        }
        ftableisselecting = false;
    });

    ftable.getSelectionModel().selectedItemProperty().addListener(e -> {
        ftableisselecting = true;
        if (!tableisselecting && genefilterset.isEmpty()) {
            table.getSelectionModel().clearSelection();
            //table.removeRowSelectionInterval(0, table.getRowCount() - 1);
            for (Function f : ftable.getSelectionModel().getSelectedItems()) {
                if (f.getGeneentries() != null) {
                    for (Gene g : f.getGeneentries()) {
                        table.getSelectionModel().select(g.getGeneGroup());

                        //Gene g = genemap.get(ref);
                        /*int i = g.getGroupIndex();
                        if( i >= 0 && i <= table.getItems().size() ) {
                           int rf = table.convertRowIndexToView(i);
                           table.addRowSelectionInterval(rf, rf);
                        }*/
                    }
                }
            }
        }
        ftableisselecting = false;
    });

    textfield.setOnKeyPressed(e -> {
        String text = textfield.getText().toLowerCase();
        if (e.getCode() == KeyCode.ENTER) {
            searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol")
                    ? searchTable(table, text, searchi, e.isAltDown(), 8, 9, 10, 16)
                    : searchTable(table, text, searchi, e.isAltDown(), 0);
        }
    });

    textfield.textProperty().addListener((observable, oldValue, newValue) -> {
        //String text = textfield.getText().toLowerCase();
        String lowerCaseFilter = newValue.toLowerCase();
        Predicate<GeneGroup> p = genegroup -> {
            if (newValue == null || newValue.isEmpty()) {
                return true;
            }

            if (searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol")) {
                if ((genegroup.getCogsymbol() != null
                        && genegroup.getCogsymbol().toLowerCase().contains(lowerCaseFilter))
                        || (genegroup.getSymbol() != null
                                && genegroup.getSymbol().toLowerCase().contains(lowerCaseFilter))
                        || (genegroup.getKoname() != null
                                && genegroup.getKoname().toLowerCase().contains(lowerCaseFilter))) {
                    return true; // Filter matches first name.
                }
            } else {
                if (genegroup.getName().toLowerCase().contains(lowerCaseFilter) || genegroup.genes.stream()
                        .anyMatch(gg -> gg.getName().toLowerCase().contains(lowerCaseFilter))) {
                    return true; // Filter matches first name.
                } /* else if (genegroup.getLastName().toLowerCase().contains(lowerCaseFilter)) {
                    return true; // Filter matches last name.
                  }*/
            }
            return false; // Does not match.
        };
        if (filter.isSelected()) {
            filteredData.setPredicate(p);
            if (label != null)
                label.setText(
                        table.getItems().size() + "/" + table.getSelectionModel().getSelectedIndices().size());
            //if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(0, text, table, genefilter, genefilterset, label, 8, 9, 10, 16 );
            //else updateFilter(0, text, table, genefilter, genefilterset, label, 0 );
        } else {
            Optional<GeneGroup> ogg = filteredData.stream().filter(p).findFirst();
            if (ogg.isPresent()) {
                GeneGroup gg = ogg.get();
                table.getSelectionModel().select(gg);
                table.scrollTo(gg);
            }
            //searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
        }
    });
    /*textfield.getDocument().addDocumentListener(new DocumentListener() {
       public void changedUpdate(DocumentEvent e) {
    String text = textfield.getText().toLowerCase();
    if( filter.isSelected() ) {
       if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(0, text, table, genefilter, genefilterset, label, 8, 9, 10, 16 );
       else updateFilter(0, text, table, genefilter, genefilterset, label, 0 );
    } else {
       searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
    }
       }
            
       public void insertUpdate(DocumentEvent e) {
    String text = textfield.getText().toLowerCase();
    if( filter.isSelected() ) {
       if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(1, text, table, genefilter, genefilterset, label, 8, 9, 10, 16);
       else updateFilter(1, text, table, genefilter, genefilterset, label, 0);
    } else {
       searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
    }
       }
            
       public void removeUpdate(DocumentEvent e) {
    String text = textfield.getText().toLowerCase();
    if( filter.isSelected() ) {
       if( searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ) updateFilter(2, text, table, genefilter, genefilterset, label, 8, 9, 10, 16 );
       else updateFilter(2, text, table, genefilter, genefilterset, label, 0);
    } else {
       searchi = searchTable( table, text, 0, false, searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? 7 : 0 );
    }
       }
    });*/

    ftextfield.textProperty().addListener(new javafx.beans.value.ChangeListener<String>() {
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            //String text = textfield.getText().toLowerCase();
            if (filter.isSelected()) {
                ffilteredData.setPredicate(function -> {
                    // If filter text is empty, display all persons.
                    if (newValue == null || newValue.isEmpty()) {
                        return true;
                    }

                    // Compare first name and last name of every person with filter text.
                    String lowerCaseFilter = newValue.toLowerCase();

                    boolean desc = function.getDesc() != null
                            && function.getDesc().toLowerCase().contains(lowerCaseFilter);
                    boolean name = function.getName() != null
                            && function.getName().toLowerCase().contains(lowerCaseFilter);
                    boolean go = function.getGo() != null
                            && function.getGo().toLowerCase().contains(lowerCaseFilter);
                    boolean ec = function.getEc() != null
                            && function.getEc().toLowerCase().contains(lowerCaseFilter);

                    if (desc || name || go || ec) {
                        return true; // Filter matches first name.
                    } /* else if (genegroup.getLastName().toLowerCase().contains(lowerCaseFilter)) {
                         return true; // Filter matches last name.
                      }*/
                    return false; // Does not match.
                });
            } else {
                //searchi = searchcolcomb.getSelectionModel().getSelectedItem().equals("Symbol") ? searchTable( table, text, 0, false, 8, 9, 10, 16 ) : searchTable( table, text, 0, false, 0 );
            }
        }
    });
    /*ftextfield.getDocument().addDocumentListener(new DocumentListener() {
       public void changedUpdate(DocumentEvent e) {
    updateFilter(0, ftextfield.getText(), ftable, rowfilter, filterset, null, 6);
       }
            
       public void insertUpdate(DocumentEvent e) {
    updateFilter(1, ftextfield.getText(), ftable, rowfilter, filterset, null, 6);
       }
            
       public void removeUpdate(DocumentEvent e) {
    updateFilter(2, ftextfield.getText(), ftable, rowfilter, filterset, null, 6);
       }
    });*/
    MenuItem kegggl = new MenuItem("KEGG gene lookup");
    kegggl.setOnAction(e -> {
        Gene g = gtable.getSelectionModel().getSelectedItem();
        try {
            Desktop.getDesktop().browse(new URI("http://www.genome.jp/dbget-bin/www_bget?" + g.keggid));
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    });
    popup.getItems().add(kegggl);
    MenuItem showgenes = new MenuItem("Show genes with same sharing");
    showgenes.setOnAction(e -> {
        genefilterset.clear();
        GeneGroup gg = table.getSelectionModel().getSelectedItem();
        for (GeneGroup g : geneset.allgenegroups) {
            if (gg.species != null && g.species != null) {
                Set<String> ggset = gg.species.keySet();
                Set<String> gset = g.species.keySet();

                if (gset.size() == ggset.size() && gset.containsAll(ggset)) {
                    genefilterset.add(g.index);
                }
            }
        }
        updateFilter(table, label);
    });
    popup.getItems().add(showgenes);
    MenuItem showshared = new MenuItem("Show shared function");
    showshared.setOnAction(e -> {
        filterset.clear();
        Set<Function> startfunc = new HashSet<Function>();
        if (isGeneview()) {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                if (gg.funcentries != null) {
                    if (startfunc.isEmpty()) {
                        startfunc.addAll(gg.funcentries);
                    } else {
                        startfunc.retainAll(gg.funcentries);
                    }
                }
                /*if (startfunc == null)
                startfunc = new HashSet<Function>(gg.funcentries);
                else {
                startfunc.retainAll(gg.funcentries);
                }*/
            }
        } else {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                Set<Function> fset = gg.getFunctions();
                if (startfunc.isEmpty()) {
                    startfunc.addAll(fset);
                } else {
                    startfunc.retainAll(fset);
                }
            }
        }
        for (Function f : geneset.funclist) {
            filterset.add(f.index);
        }
        updateFilter(ftable, null);
    });
    popup.getItems().add(showshared);
    MenuItem showall = new MenuItem("Show all functions");
    showall.setOnAction(e -> {
        filterset.clear();
        Set<Function> startfunc = null;
        if (isGeneview()) {
            for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
                if (gg.funcentries != null) {
                    for (Function f : gg.funcentries) {
                        filterset.add(f.index);
                    }
                }
            }
        } else {
            for (GeneGroup gg : table.getSelectionModel().getSelectedItems()) {
                Set<Function> fset = gg.getFunctions();
                for (Function f : fset) {
                    filterset.add(f.index);
                }
            }
        }
        updateFilter(ftable, null);
    });
    popup.getItems().add(showall);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showgenegroups = new MenuItem("Show gene groups in proximity");
    showgenegroups.setOnAction(e -> {
        proxi(filteredData, false);
        updateFilter(table, label);
    });
    popup.getItems().add(showgenegroups);
    MenuItem selgenegroups = new MenuItem("Select gene groups in proximity");
    selgenegroups.setOnAction(e -> {
        genefilterset.clear();
        proxi(filteredData, false);
        for (int i : genefilterset) {
            table.getSelectionModel().select(i);
        }
        //table.tableChanged( new TableModelEvent( table.getModel() ) );
        if (label != null)
            label.setText(table.getItems().size() + "/" + table.getSelectionModel().getSelectedItems().size());
        //updateFilter(table, genefilter, label);
    });
    popup.getItems().add(selgenegroups);
    MenuItem selgenes = new MenuItem("Select genes in proximity");
    selgenes.setOnAction(e -> {
        genefilterset.clear();
        proxi(filteredData, true);
        for (int i : genefilterset) {
            table.getSelectionModel().select(i);
        }
        //table.tableChanged( new TableModelEvent( table.getModel() ) );
        if (label != null)
            label.setText(table.getItems().size() + "/" + table.getSelectionModel().getSelectedItems().size());
        //updateFilter(table, genefilter, label);
    });
    popup.getItems().add(selgenes);
    MenuItem addgene = new MenuItem("Add gene groups in proximity");
    addgene.setOnAction(e -> {
        proxi(filteredData, false);
        updateFilter(table, label);
    });
    popup.getItems().add(addgene);
    MenuItem remgene = new MenuItem("Remove gene groups in proximity");
    remgene.setOnAction(e -> {
        ObservableList<Integer> rr = table.getSelectionModel().getSelectedIndices();
        if (genefilterset.isEmpty()) {
            Set<Integer> ii = new HashSet<>();
            for (int r : rr)
                ii.add(r);
            for (int i = 0; i < geneset.genelist.size(); i++) {
                if (!ii.contains(i))
                    genefilterset.add(i);
            }
        }
        proxi(filteredData, false);
        updateFilter(table, label);
    });
    popup.getItems().add(remgene);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showrel = new MenuItem("Show related genes");
    showrel.setOnAction(e -> {
        genefilterset.clear();
        relati(gtable, geneset.genelist, genefilterset, geneset.uclusterlist, false);
        updateFilter(gtable, label);
    });
    popup.getItems().add(showrel);
    MenuItem addrel = new MenuItem("Add related genes");
    addrel.setOnAction(e -> {
        relati(gtable, geneset.genelist, genefilterset, geneset.uclusterlist, false);
        updateFilter(gtable, label);
    });
    popup.getItems().add(addrel);
    MenuItem remrel = new MenuItem("Remove related genes");
    remrel.setOnAction(e -> {
        ObservableList<Integer> rr = gtable.getSelectionModel().getSelectedIndices();
        if (genefilterset.isEmpty()) {
            Set<Integer> ii = new HashSet<>();
            for (int r : rr)
                ii.add(r);
            for (int i = 0; i < geneset.genelist.size(); i++) {
                if (!ii.contains(i))
                    genefilterset.add(i);
            }
        }
        relati(gtable, geneset.genelist, genefilterset, geneset.uclusterlist, true);
        updateFilter(table, label);
    });
    popup.getItems().add(remrel);
    popup.getItems().add(new SeparatorMenuItem());
    MenuItem showcloserel = new MenuItem("Show closely related genes");
    showcloserel.setOnAction(e -> {
        genefilterset.clear();
        Set<String> ct = new HashSet<>();
        for (Gene gg : gtable.getSelectionModel().getSelectedItems()) {
            // genefilterset.add( gg.index );
            Tegeval tv = gg.tegeval;
            for (Set<String> uset : geneset.iclusterlist) {
                if (uset.contains(tv.name)) {
                    ct.addAll(uset);
                    break;
                }
            }
        }

        for (Gene g : geneset.genelist) {
            Tegeval tv = g.tegeval;
            if (ct.contains(tv.name)) {
                genefilterset.add(g.index);
                break;
            }
        }

        updateFilter(table, label);
    });
    popup.getItems().add(showcloserel);
    MenuItem showdist = new MenuItem("Show distance matrix");
    showdist.setOnAction(e -> {
        JTextArea textarea = new JTextArea();

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

        JScrollPane scrollpane = new JScrollPane(textarea);
        Gene gg = gtable.getSelectionModel().getSelectedItem();
        if (gg.getSpecies() != null) {
            for (String s : geneset.corrInd) {
                if (s.equals(geneset.corrInd.get(0)))
                    textarea.append(s);
                else
                    textarea.append("\t" + s);
            }

            int i = 0;
            int j = 0;

            int len = 16;
            double[] min = new double[len];
            double[] max = new double[len];

            for (i = 0; i < len; i++) {
                min[i] = Double.MAX_VALUE;
                max[i] = 0.0;
            }

            double[] corrarr = gg.corrarr;
            boolean symmetrize = true;
            if (symmetrize) {
                for (i = 0; i < len; i++) {
                    for (int k = i + 1; k < len; k++) {
                        corrarr[i * len + k] = (corrarr[k * len + i] + corrarr[i * len + k]) / 2.0;
                        corrarr[k * len + i] = corrarr[i * len + k];
                    }
                }
            }

            for (i = 0; i < len; i++) {
                for (int k = 0; k < len; k++) {
                    if (corrarr[i * len + k] < min[i])
                        min[i] = corrarr[i * len + k];
                    if (corrarr[i * len + k] > max[i])
                        max[i] = corrarr[i * len + k];
                }

                /*for (int k = 0; k < len; k++) {
                   corrarr[i * 16 + k] = corrarr[i * 16 + k] - min;
                }*/
            }

            i = 0;
            for (double d : corrarr) {
                double dval = d;
                if (i % len == 0)
                    textarea.append("\n" + dval);
                else
                    textarea.append("\t" + dval);

                i++;
            }
            textarea.append("\n");

            i = 0;
            for (double d : corrarr) {
                double dval = Math.exp((d - min[i / len]) / 20.0 + 1.0) / 100.0; // 0.0 ?
                // 0.0 :
                // 100.0/d;
                if (i % len == 0)
                    textarea.append("\n" + dval);
                else
                    textarea.append("\t" + dval);

                i++;
            }
            double[] newcorr = Arrays.copyOf(corrarr, corrarr.length);
            textarea.append("\nD matrix\n");
            i = 0;
            for (double d : corrarr) {
                double dval = max[i / len] - d;
                newcorr[i] = dval;
                if (i % len == 0)
                    textarea.append("\n" + dval);
                else
                    textarea.append("\t" + dval);

                i++;
            }

            TreeUtil treeutil = new TreeUtil();
            treeutil.neighborJoin(newcorr, geneset.corrInd, null, true, true);
        }

        /*
         * int[] rr = table.getSelectedRows(); for( int r : rr ) { int
         * cr = table.convertRowIndexToModel(r); Gene gg =
         * genelist.get(cr); if( gg.species != null ) { textarea.append(
         * gg.name + ":\n" ); for( String sp : gg.species.keySet() ) {
         * Teginfo stv = gg.species.get( sp ); for( Tegeval tv :
         * stv.tset ) { textarea.append( ">" + tv.cont + " " + tv.teg +
         * " " + tv.eval + "\n" ); for( int i = 0; i < tv.seq.length();
         * i+=70 ) { int end = Math.min(i+70,tv.seq.length());
         * textarea.append( tv.seq.substring(i, end)+"\n" ); //new
         * String( tv.seq, i, Math.min(i+70,tv.seq.length()) )+"\n"); }
         * //textarea.append( ">" + tv.cont + " " + tv.teg + " " +
         * tv.eval + "\n" + tv.seq + "\n" ); } } } }
         */
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(scrollpane);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });

    /*
     * final List<String> reglist = new ArrayList<String>(); final
     * Map<String,Gene> regidx = new TreeMap<String,Gene>();
     * 
     * for( Gene g : geneset.genelist ) { if( g.species != null ) { for( String key
     * : g.species.keySet() ) { Set<Tegeval> stv = g.species.get(key); for(
     * Tegeval tv : stv ) { regidx.put(tv.cont, g); } } } }
     * 
     * for( String key : regidx.keySet() ) { reglist.add(key); }
     * 
     * final JTable contigtable = new JTable();
     * contigtable.setAutoCreateRowSorter( true ); contigtable.setModel( new
     * TableModel() {
     * 
     * @Override public int getRowCount() { return reglist.size(); }
     * 
     * @Override public int getColumnCount() { return 1; }
     * 
     * @Override public String getColumnName(int columnIndex) { return
     * "Region"; }
     * 
     * @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 reglist.get(rowIndex); }
     * 
     * @Override public void setValueAt(Object aValue, int rowIndex, int
     * columnIndex) { // TODO Auto-generated method stub
     * 
     * }
     * 
     * @Override public void addTableModelListener(TableModelListener l) {
     * // TODO Auto-generated method stub
     * 
     * }
     * 
     * @Override public void removeTableModelListener(TableModelListener l)
     * { // TODO Auto-generated method stub
     * 
     * } });
     * 
     * contigtable.getSelectionModel().addListSelectionListener( new
     * ListSelectionListener() {
     * 
     * @Override public void valueChanged(ListSelectionEvent e) {
     * genefilterset.clear(); int[] rr = contigtable.getSelectedRows(); for(
     * int r : rr ) { String s = (String)contigtable.getValueAt(r, 0); Gene
     * g = regidx.get( s );
     * 
     * genefilterset.add( g.index ); updateFilter(table, genefilter, label);
     * //int k = table.convertRowIndexToView(g.index); //if( k != -1
     * )table.addRowSelectionInterval(k, k); } } }); JScrollPane
     * contigscroll = new JScrollPane( contigtable );
     * 
     * JSplitPane mainsplit = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT );
     * mainsplit.setLeftComponent( contigscroll );
     * mainsplit.setRightComponent( splitpane );
     */
}