Example usage for javafx.stage FileChooser getExtensionFilters

List of usage examples for javafx.stage FileChooser getExtensionFilters

Introduction

In this page you can find the example usage for javafx.stage FileChooser getExtensionFilters.

Prototype

public ObservableList<ExtensionFilter> getExtensionFilters() 

Source Link

Document

Gets the extension filters used in the displayed file dialog.

Usage

From source file:de.bayern.gdi.gui.Controller.java

/**
 * Handle config saving./*  w w w  .  java  2s.  com*/
 *
 * @param event The event.
 */
@FXML
protected void handleSaveConfig(ActionEvent event) {
    extractStoredQuery();
    extractBoundingBox();
    extractCql();
    if (validateInput() && validateCqlInput()) {
        FileChooser fileChooser = new FileChooser();
        DirectoryChooser dirChooser = new DirectoryChooser();
        File downloadDir;
        File initDir;

        dirChooser.setTitle(I18n.getMsg("gui.save-dir"));

        if (downloadConfig == null) {
            downloadDir = dirChooser.showDialog(getPrimaryStage());
            String basedir = Config.getInstance().getServices().getBaseDirectory();
            initDir = new File(basedir.isEmpty() ? System.getProperty(USER_DIR) : basedir);
            File uniqueName = Misc.uniqueFile(downloadDir, "config", "xml", null);
            fileChooser.setInitialFileName(uniqueName.getName());
        } else {
            File downloadInitDir = new File(downloadConfig.getDownloadPath());
            if (!downloadInitDir.exists()) {
                downloadInitDir = new File(System.getProperty(USER_DIR));
            }
            dirChooser.setInitialDirectory(downloadInitDir);
            downloadDir = dirChooser.showDialog(getPrimaryStage());

            String path = downloadConfig.getFile().getAbsolutePath();
            path = path.substring(0, path.lastIndexOf(File.separator));
            initDir = new File(path);
            fileChooser.setInitialFileName(downloadConfig.getFile().getName());
        }
        fileChooser.setInitialDirectory(initDir);
        FileChooser.ExtensionFilter xmlFilter = new FileChooser.ExtensionFilter("xml files (*.xml)", "*.xml");
        fileChooser.getExtensionFilters().add(xmlFilter);
        fileChooser.setSelectedExtensionFilter(xmlFilter);
        fileChooser.setTitle(I18n.getMsg("gui.save-conf"));
        File configFile = fileChooser.showSaveDialog(getPrimaryStage());
        if (configFile == null) {
            return;
        }

        if (!configFile.toString().endsWith(".xml")) {
            configFile = new File(configFile.toString() + ".xml");
        }

        this.dataBean.setProcessingSteps(extractProcessingSteps());

        String savePath = downloadDir.getPath();
        DownloadStep ds = dataBean.convertToDownloadStep(savePath);
        try {
            ds.write(configFile);
        } catch (IOException ex) {
            log.warn(ex.getMessage(), ex);
        }
    }
}

From source file:snpviewer.SnpViewer.java

public void loadColourScheme(ActionEvent e) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters()
            .add(new FileChooser.ExtensionFilter("SNP Viewer Colour Scheme", "*.svcols"));
    fileChooser.setTitle("Open SNP Viewer Colour Scheme (.svcols) file");
    File loadFile = fileChooser.showOpenDialog(mainWindow);
    if (loadFile != null) {
        try {//  www.j  a  v a 2s. co m
            ObjectInputStream is = new ObjectInputStream(
                    new BufferedInputStream(new FileInputStream(loadFile)));
            ArrayList<Color> loadedColors = new ArrayList<>();
            for (Color c : colorComp) {
                String colorString = (String) is.readObject();
                loadedColors.add(Color.valueOf(colorString));
            }
            for (int ci = 0; ci < loadedColors.size(); ci++) {
                colorComponantSelector.getSelectionModel().clearAndSelect(ci);
                colorPicker.setValue(loadedColors.get(ci));
                colorPicker.fireEvent(new ActionEvent());
            }
            colorComponantSelector.getSelectionModel().selectFirst();
            colorComp.clear();
            colorComp.addAll(loadedColors);
            is.close();
            saveProject();
            removeSavedChromosomeImages();
            refreshView((String) chromosomeSelector.getSelectionModel().getSelectedItem(), true);
        } catch (IOException | ClassNotFoundException ex) {

        }
    }
}

From source file:snpviewer.SnpViewer.java

public void addInputFiles(final boolean isAffected) {
    setProgressMode(true);//from  ww  w. j a v  a 2  s.c  om
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters()
            .add(new FileChooser.ExtensionFilter("Text Files", "*.txt", "AutoSNPa Files", "*.xls"));
    fileChooser.setTitle("Select one or more input (birdseed) files");
    List<File> chosen = fileChooser.showOpenMultipleDialog(null);
    if (chosen == null) {
        setProgressMode(false);
        return;
    }
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            setProgressMode(false);
        };
    });
    ArrayList<File> inputFiles = new ArrayList<>();
    inputFiles.addAll(chosen);
    ArrayList<File> duplicates = new ArrayList<>();
    ArrayList<Integer> indicesToRemove = new ArrayList<>();
    for (int i = 0; i < inputFiles.size(); i++) {
        for (SnpFile s : affFiles) {
            if (inputFiles.get(i).getName().equals(s.getInputFileName())) {
                duplicates.add(inputFiles.get(i));
                indicesToRemove.add(i);
            }
        }
        for (SnpFile s : unFiles) {
            if (inputFiles.get(i).getName().equals(s.getInputFileName())) {
                duplicates.add(inputFiles.get(i));
                indicesToRemove.add(i);
            }
        }
    }
    if (!duplicates.isEmpty()) {
        StringBuilder duplicateString = new StringBuilder();
        for (File d : duplicates) {
            duplicateString.append(d.getName()).append("\n");
        }
        Collections.sort(indicesToRemove, Collections.reverseOrder());
        for (int i : indicesToRemove) {
            inputFiles.remove(i);
        }
        DialogResponse response = Dialogs.showWarningDialog(null,
                "This project already includes the following file(s) with "
                        + "matching names to the file(s) you have just tried to add:" + "\n\n" + duplicateString
                        + "\nIf you want to change the affected "
                        + "status of a file please remove it first.  Any remaining "
                        + "(non-duplicate) files will be processed if you click 'OK'.",
                "Duplicate Input File", "SnpViewer", Dialogs.DialogOptions.OK_CANCEL);
        if (!response.equals(DialogResponse.OK)) {
            setProgressMode(false);
            return;
        }
    }
    if (inputFiles.isEmpty()) {
        setProgressMode(false);
        return;
    }
    final Iterator iter = inputFiles.iterator();
    File input = (File) iter.next();
    int fileCounter = 1;
    if (snpViewSaveDirectory == null) {
        Dialogs.showWarningDialog(null, "Before processing input files " + "please create a project",
                "Create Project", "SNP Viewer");

        boolean success = startNewProject();

        if (!success) {
            setProgressMode(false);
            return;
        }
    }

    addInputFilesWithIterator(isAffected, input, iter, fileCounter, inputFiles.size());
}

From source file:snpviewer.SnpViewer.java

public void drawPaneToPng() {
    if (chromosomeSelector.getSelectionModel().isEmpty()) {
        return;//from ww  w. j a  va  2  s.c  om
    }
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PNG Image Files (*.png)", "*.png");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Save View as Image (.png) File...");
    File pngFile = fileChooser.showSaveDialog(mainWindow);
    if (pngFile == null) {
        return;
    } else if (!pngFile.getName().endsWith(".png")) {
        pngFile = new File(pngFile.getAbsolutePath() + ".png");
    }
    WritableImage image = chromSplitPane.snapshot(null, null);
    if (image == null) {
        Dialogs.showErrorDialog(null, "Error attempting to convert" + " dynamic view to image file",
                "PNG conversion failed", "SNP Viewer");
        return;
    }
    try {
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", pngFile);
        Dialogs.showInformationDialog(null, "Sucessfully saved current view " + "to " + pngFile.getName(),
                "Image Saved", "SNP Viewer");
    } catch (IOException ex) {
        Dialogs.showErrorDialog(null, "Error attempting to convert" + " dynamic view to image file",
                "PNG conversion failed", "SNP Viewer", ex);
    }
}

From source file:snpviewer.SnpViewer.java

public void loadProject() {
    if (projectRunning) {
        /*setProgressMode(true);
        DialogResponse response = Dialogs.showConfirmDialog(null,
        "Do you want to save your current project before starting a new one?", 
            "Save Current Project?", "SNP View");
        if (DialogResponse.YES.equals(response)){
        boolean saved = saveProject();/* www.  j ava  2 s  .c  o  m*/
        if (! saved){
            setProgressMode(false);
            return;
        }else{
            Dialogs.showInformationDialog(null, projectFile.getName() + " saved sucessfully", 
                    "Save Successful", "SNP View");
        }
        }else if (DialogResponse.CANCEL.equals(response)){
        setProgressMode(false);
        return;
        }*/
    }
    loadProjectButton.setDisable(true);
    newProjectButton.setDisable(true);
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("SNP Viewer Projects", "*.svproj"));
    fileChooser.setTitle("Open SNP Viewer Project (.svproj) file");
    //setProgressMode(false);
    File loadFile = fileChooser.showOpenDialog(mainWindow);
    loadProjectButton.setDisable(false);
    newProjectButton.setDisable(false);
    if (loadFile != null) {
        try {
            ObjectInputStream is = new ObjectInputStream(
                    new BufferedInputStream(new FileInputStream(loadFile)));
            try {
                projectFile = null;
                projectLabel.setText("Project: none");
                chromSplitPane.getItems().clear();
                labelSplitPane.getItems().clear();
                clearDragSelectRectangle();
                savedRegions.clear();
                savedRegionsDisplay.clear();
                savedRegionsReference.clear();
                selectionOverlayPane.getChildren().clear();
                selectionOverlayPane.getChildren().add(dragSelectRectangle);

                resetObservables();
                genomeVersion = "";
                qualityFilter = null;
                noFilteringRadio.setSelected(true);
                chromosomeSelector.getItems().clear();
                projectFile = (File) is.readObject();//get rid of this?
                projectFile = loadFile;//allow relative referencing

                ArrayList<Color> loadedColors = new ArrayList<>();
                ArrayList<SnpFile> tempAff = new ArrayList<>();
                ArrayList<SnpFile> tempUn = new ArrayList<>();
                tempAff.addAll((ArrayList<SnpFile>) is.readObject());
                tempUn.addAll((ArrayList<SnpFile>) is.readObject());
                ArrayList<SnpFile> tempBoth = new ArrayList<>();
                tempBoth.addAll(tempAff);
                tempBoth.addAll(tempUn);
                genomeVersion = (String) is.readObject();
                qualityFilter = (Double) is.readObject();
                buildLabel.setText(genomeVersion);
                snpViewSaveDirectory = (File) is.readObject();
                savedRegions = (ArrayList<RegionSummary>) is.readObject();
                String projectName = projectFile.getName().replaceAll(".svproj", "");
                if (!snpViewSaveDirectory.exists()) {
                    snpViewSaveDirectory = new File(
                            projectFile.getParentFile() + "/" + projectName + " SNP Viewer files");
                    if (!snpViewSaveDirectory.exists()) {
                        DialogResponse response = Dialogs.showErrorDialog(null,
                                "Can't find project directory (" + snpViewSaveDirectory.getName()
                                        + ") - do you " + "want to try to find it?",
                                "Project directory " + "not found", "SnpViewer", Dialogs.DialogOptions.YES_NO);
                        if (DialogResponse.YES.equals(response)) {
                            DirectoryChooser dirChooser = new DirectoryChooser();
                            dirChooser.setTitle("Locate Project Folder");
                            snpViewSaveDirectory = dirChooser.showDialog(mainWindow);
                            if (snpViewSaveDirectory == null) {
                                returnToInitialState();
                                return;
                            }
                        } else {
                            returnToInitialState();
                            return;
                        }
                    }
                }
                boolean check = checkProjectFolder(snpViewSaveDirectory, tempBoth);
                if (!check) {
                    Dialogs.showErrorDialog(null, "Corrupt project" + " folder - missing files.",
                            "Invalid " + "project folder.", "SnpViewer");
                    returnToInitialState();
                    return;
                }
                for (Color c : colorComp) {
                    String colorString = (String) is.readObject();
                    loadedColors.add(Color.valueOf(colorString));
                }
                for (int ci = 0; ci < loadedColors.size(); ci++) {
                    colorComponantSelector.getSelectionModel().clearAndSelect(ci);
                    colorPicker.setValue(loadedColors.get(ci));
                    colorPicker.fireEvent(new ActionEvent());
                }
                affObserve.addAll(tempAff);
                unObserve.addAll(tempUn);
                colorComponantSelector.getSelectionModel().selectFirst();
                colorComp.clear();
                colorComp.addAll(loadedColors);
                is.close();
                setQualityLabel();
                checkQualitySelection();
                saveProject();
                projectLabel.setText("Project: " + projectFile.getName());
                //addToChromosomeSelector(affFiles);
                //addToChromosomeSelector(unFiles);
                if (!chromosomeSelector.getItems().isEmpty()) {
                    chromosomeSelector.getSelectionModel().selectFirst();
                }
                if (chromosomeSelector.isDisabled()) {
                    chromosomeSelector.setDisable(false);
                }
                //setProgressMode(false);
                if (affObserve.isEmpty() && unObserve.isEmpty()) {
                    resetView();
                }
                projectRunning = true;

            } catch (IOException | ClassNotFoundException ex) {
                resetView();
                projectLabel.setText("Project: none");
                savedRegions.clear();
                savedRegionsDisplay.clear();
                savedRegionsReference.clear();
                resetObservables();
                genomeVersion = "";
                qualityFilter = null;
                noFilteringRadio.setSelected(true);
                chromosomeSelector.getItems().clear();
                ex.printStackTrace();
                Dialogs.showErrorDialog(null, "Could not load project file", "Load Failed", "SNP Viewer", ex);
            }
        } catch (IOException ex) {
            resetView();
            projectLabel.setText("Project: none");
            savedRegions.clear();
            savedRegionsDisplay.clear();
            savedRegionsReference.clear();
            resetObservables();
            genomeVersion = "";
            qualityFilter = null;
            noFilteringRadio.setSelected(true);
            chromosomeSelector.getItems().clear();
            ex.printStackTrace();
            Dialogs.showErrorDialog(null, "Could not load project file - IO error", "Load Failed", "SNP Viewer",
                    ex);
        }
    }
}

From source file:snpviewer.SnpViewer.java

public boolean startNewProject() {
    affFiles.clear();/*  ww  w  .  j a  v a  2 s  .  c om*/
    unFiles.clear();
    resetObservables();
    genomeVersion = "";
    qualityFilter = null;
    noFilteringRadio.setSelected(true);
    chromSplitPane.getItems().clear();
    labelSplitPane.getItems().clear();
    chromosomeSelector.getItems().clear();
    snpViewSaveDirectory = null;
    clearDragSelectRectangle();
    savedRegions.clear();
    savedRegionsDisplay.clear();
    savedRegionsReference.clear();
    selectionOverlayPane.getChildren().clear();
    selectionOverlayPane.getChildren().add(dragSelectRectangle);

    if (projectRunning) {
        setProgressMode(true);
    }
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("SNP Viewer Projects (*.svproj)",
            "*.svproj");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Save New SNP Viewer (.svproj) Project As...");
    projectFile = fileChooser.showSaveDialog(mainWindow);
    if (projectFile != null) {
        if (!projectFile.getName().endsWith(".svproj")) {
            projectFile = new File(projectFile.getAbsolutePath() + ".svproj");
        }
        try {
            String projectName = projectFile.getName().replaceAll(".svproj", "");
            File snpViewDir = new File(projectFile.getParentFile() + "/" + projectName + " SNP Viewer files");
            if (snpViewDir.exists()) {
                FileUtils.deleteDirectory(snpViewDir);
            }
            boolean madeDir = snpViewDir.mkdir();
            if (madeDir) {
                snpViewSaveDirectory = snpViewDir;
            } else {
                //display error?
                return false;
            }
        } catch (Exception ex) {
            Dialogs.showErrorDialog(null, "Project Directory Creation Failed", "Error Creating New Project",
                    "Snp Viewer", ex);
        }
        return saveProject(projectFile);
    } else {
        resetView();
        return false;
    }

}

From source file:snpviewer.SnpViewer.java

public void saveColours(ActionEvent e) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save Colour Scheme (.svcols) As...");
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("SNP Viewer Colour Scheme",
            "*.svcols");
    fileChooser.getExtensionFilters().add(extFilter);
    File colorFile = fileChooser.showSaveDialog(mainWindow);
    if (colorFile != null) {
        if (!colorFile.getName().endsWith(".svcols")) {
            colorFile = new File(colorFile.getAbsolutePath() + ".svcols");
        }//from ww  w.j a  v  a2s.  c om

        try {
            FileOutputStream fos = new FileOutputStream(colorFile);
            try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fos))) {
                for (Color c : colorComp) {
                    out.writeObject(c.toString());
                }
                out.close();
                projectLabel.setText("Project: " + projectFile.getName());
            }
        } catch (IOException ex) {
            Dialogs.showErrorDialog(null, "Could not save colour scheme - IO error", "Save Failed",
                    "SNP Viewer", ex);
        }
    }
}

From source file:snpviewer.SnpViewer.java

public boolean saveProject() {
    if (projectFile != null) {
        return saveProject(projectFile);
    } else {/*  w  w  w  .j a  va2s . c o  m*/
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Save Snp Viewer Project (.svproj) As...");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("SNP Viewer Projects",
                "*.svproj");
        fileChooser.getExtensionFilters().add(extFilter);
        projectFile = fileChooser.showSaveDialog(mainWindow);
        if (projectFile != null) {
            if (!projectFile.getName().endsWith(".svproj")) {
                projectFile = new File(projectFile.getAbsolutePath() + ".svproj");
            }
            return saveProject(projectFile);

        } else {
            return false;
        }
    }
}

From source file:snpviewer.SnpViewer.java

public void writeRegionToFile(final String chromosome, final double start, final double end) {
    /* get coordinates of selection and report back
     * write SNPs in region to file/*from w ww. j a v a 2s. c om*/
     */
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Excel  (*.xlsx)", "*.xlsx");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Write region to Excel file (.xlsx)...");
    File rFile = fileChooser.showSaveDialog(mainWindow);
    if (rFile == null) {
        return;
    } else if (!rFile.getName().endsWith(".xlsx")) {
        rFile = new File(rFile.getAbsolutePath() + ".xlsx");
    }
    final File regionFile = rFile;
    final Task<Boolean> writeTask = new Task() {
        @Override
        protected Boolean call() throws Exception {
            try {

                updateProgress(-1, -1);
                ArrayList<SnpFile> bothFiles = new ArrayList<>();
                bothFiles.addAll(affFiles);
                bothFiles.addAll(unFiles);
                TreeMap<Integer, HashMap<String, String>> coordMap = new TreeMap();
                /*coordmap - key is position, key of hashmap 
                 * is input filename and value call
                 */
                HashMap<Integer, String> coordToId = new HashMap<>();
                double progress = 0;
                double total = bothFiles.size() * 5;
                try {
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(regionFile));
                    Workbook wb = new XSSFWorkbook();
                    Sheet sheet = wb.createSheet();
                    int rowNo = 0;
                    Row row = sheet.createRow(rowNo++);
                    for (SnpFile f : bothFiles) {
                        if (isCancelled()) {
                            return false;
                        }
                        updateProgress(++progress, total);
                        updateMessage("Reading region in " + f.inputFile.getName());
                        List<SnpFile.SnpLine> lines = f.getSnpsInRegion(chromosome, (int) start, (int) end);
                        for (SnpFile.SnpLine snpLine : lines) {
                            if (isCancelled()) {
                                return false;
                            }
                            Integer coord = snpLine.getPosition();
                            if (!coordMap.containsKey(coord)) {
                                coordMap.put(coord, new HashMap<String, String>());
                            }
                            String filename = f.inputFile.getName();
                            String rsId = snpLine.getId();
                            String call = snpLine.getCall();
                            coordMap.get(coord).put(filename, call);
                            coordToId.put(coord, rsId);
                        }
                    }
                    Cell cell = row.createCell(0);
                    cell.setCellValue(
                            "chr" + chromosome + ":" + coordMap.firstKey() + "-" + coordMap.lastKey());
                    row = sheet.createRow(rowNo++);
                    cell = row.createCell(0);
                    cell.setCellValue(
                            coordToId.get(coordMap.firstKey()) + ";" + coordToId.get(coordMap.lastKey()));
                    row = sheet.createRow(rowNo++);
                    int colNo = 0;
                    cell = row.createCell(colNo++);
                    cell.setCellValue("Position");
                    cell = row.createCell(colNo++);
                    cell.setCellValue("rsID");
                    for (SnpFile f : bothFiles) {
                        cell = row.createCell(colNo++);
                        if (f.getSampleName() != null && f.getSampleName().length() > 0) {
                            cell.setCellValue(f.getSampleName());
                        } else {
                            cell.setCellValue(f.getInputFileName());
                        }
                    }
                    progress = coordMap.size();
                    total = 5 * coordMap.size();
                    updateMessage("Writing region to file...");
                    for (Entry current : coordMap.entrySet()) {
                        if (isCancelled()) {
                            return false;
                        }
                        progress += 4;
                        updateProgress(progress, total);
                        row = sheet.createRow(rowNo++);
                        colNo = 0;
                        Integer coord = (Integer) current.getKey();
                        cell = row.createCell(colNo++);
                        cell.setCellValue(coord);
                        String rsId = coordToId.get(coord);
                        cell = row.createCell(colNo++);
                        cell.setCellValue(rsId);
                        HashMap<String, String> fileToCall = (HashMap<String, String>) current.getValue();
                        for (SnpFile f : bothFiles) {
                            cell = row.createCell(colNo++);
                            if (fileToCall.containsKey(f.inputFile.getName())) {
                                cell.setCellValue(fileToCall.get(f.inputFile.getName()));
                            } else {
                                cell.setCellValue("-");
                            }
                        }
                    }
                    CellRangeAddress[] regions = { new CellRangeAddress(0, rowNo, 2, 2 + bothFiles.size()) };
                    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

                    ConditionalFormattingRule rule1 = sheetCF
                            .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AA\"");
                    PatternFormatting fill1 = rule1.createPatternFormatting();
                    fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
                    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                    ConditionalFormattingRule rule2 = sheetCF
                            .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"BB\"");
                    PatternFormatting fill2 = rule2.createPatternFormatting();
                    fill2.setFillBackgroundColor(IndexedColors.PALE_BLUE.index);
                    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                    ConditionalFormattingRule rule3 = sheetCF
                            .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AB\"");
                    PatternFormatting fill3 = rule3.createPatternFormatting();
                    fill3.setFillBackgroundColor(IndexedColors.ROSE.index);
                    fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                    sheetCF.addConditionalFormatting(regions, rule3, rule2);
                    sheetCF.addConditionalFormatting(regions, rule1);
                    wb.write(out);
                    out.close();
                    return true;
                } catch (IOException ex) {
                    return false;
                }
            } catch (Exception ex) {
                return false;
            }
        }
    };//end of task

    setProgressMode(true);
    progressBar.progressProperty().bind(writeTask.progressProperty());
    progressMessage.textProperty().bind(writeTask.messageProperty());
    writeTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            if (e.getSource().getValue() == true) {
                Dialogs.showInformationDialog(null,
                        "Region written to file " + "(" + regionFile.getName() + ") successfully",
                        "Region Written", "SNP Viewer");
            } else {
                Dialogs.showErrorDialog(null, "Region write failed.", "Write Failed", "SNP Viewer");
            }
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("");

        }

    });
    writeTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("Region write failed!");
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer",
                    e.getSource().getException());

        }

    });
    writeTask.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            progressMessage.setText("Region write cancelled");
            progressTitle.setText("Cancelled");
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer");
        }

    });
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            writeTask.cancel();

        }
    });
    progressTitle.setText("Writing region to .xlsx file");
    new Thread(writeTask).start();
}

From source file:snpviewer.SnpViewer.java

public void writeSavedRegionsToFile() {
    if (savedRegions.size() < 1) {
        Dialogs.showErrorDialog(null, "No Saved Regions exist to write!", "No Saved Regions", "SnpViewer");
        return;//from w  w w  .  ja va2s  . c  o  m
    }
    final int flanks = 10;
    FileChooser fileChooser = new FileChooser();
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Excel (*.xlsx)", "*.xlsx");
    fileChooser.getExtensionFilters().add(extFilter);
    fileChooser.setTitle("Write regions to Excel file (.xlsx)...");
    File rFile = fileChooser.showSaveDialog(mainWindow);
    if (rFile == null) {
        return;
    } else if (!rFile.getName().endsWith(".xlsx")) {
        rFile = new File(rFile.getAbsolutePath() + ".xlsx");
    }
    final File regionFile = rFile;
    final Task<Boolean> writeTask = new Task() {
        @Override
        protected Boolean call() throws Exception {
            try {
                updateProgress(-1, -1);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(regionFile));
                Workbook wb = new XSSFWorkbook();
                //first create a summary sheet of all regions
                Sheet sheet = wb.createSheet();
                Row row = null;
                int rowNo = 0;
                int sheetNo = 0;
                wb.setSheetName(sheetNo++, "Summary");
                row = sheet.createRow(rowNo++);
                String header[] = { "Coordinates", "rsIDs", "Size (Mb)" };
                for (int col = 0; col < header.length; col++) {
                    Cell cell = row.createCell(col);
                    cell.setCellValue(header[col]);
                }
                for (int i = 0; i < savedRegions.size(); i++) {
                    row = sheet.createRow(rowNo++);
                    int col = 0;
                    Cell cell = row.createCell(col++);
                    cell.setCellValue("chr" + savedRegions.get(i).getCoordinateString());
                    cell = row.createCell(col++);
                    cell.setCellValue(savedRegions.get(i).getIdLine());
                    cell = row.createCell(col++);
                    double mB = (double) savedRegions.get(i).getLength() / 1000000;
                    cell.setCellValue(mB);
                }

                ArrayList<SnpFile> bothFiles = new ArrayList<>();
                bothFiles.addAll(affFiles);
                bothFiles.addAll(unFiles);
                String prevChrom = new String();
                double prog = 0;
                double total = savedRegions.size() * bothFiles.size() * 2;
                updateProgress(prog, total);
                int regCounter = 0;
                for (RegionSummary reg : savedRegions) {
                    updateMessage("Writing region " + ++regCounter + " of " + savedRegions.size());
                    //create a sheet for each chromosome
                    if (!reg.getChromosome().equalsIgnoreCase(prevChrom)) {
                        if (!prevChrom.isEmpty()) {

                            CellRangeAddress[] regions = {
                                    new CellRangeAddress(0, rowNo, 2, 2 + bothFiles.size()) };
                            SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

                            ConditionalFormattingRule rule1 = sheetCF
                                    .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AA\"");
                            PatternFormatting fill1 = rule1.createPatternFormatting();
                            fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
                            fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                            ConditionalFormattingRule rule2 = sheetCF
                                    .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"BB\"");
                            PatternFormatting fill2 = rule2.createPatternFormatting();
                            fill2.setFillBackgroundColor(IndexedColors.PALE_BLUE.index);
                            fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                            ConditionalFormattingRule rule3 = sheetCF
                                    .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AB\"");
                            PatternFormatting fill3 = rule3.createPatternFormatting();
                            fill3.setFillBackgroundColor(IndexedColors.ROSE.index);
                            fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                            sheetCF.addConditionalFormatting(regions, rule3, rule2);
                            sheetCF.addConditionalFormatting(regions, rule1);
                        }
                        rowNo = 0;
                        sheet = wb.createSheet();
                        wb.setSheetName(sheetNo++, reg.getChromosome());
                        prevChrom = reg.getChromosome();

                    } else {//pad regions with an empty line
                        rowNo++;
                    }
                    TreeMap<Integer, HashMap<String, String>> coordMap = new TreeMap();
                    /*coordmap - key is position, key of hashmap 
                     * is input filename and value call
                     */
                    HashMap<Integer, String> coordToId = new HashMap<>();
                    //coordinate to rs ID

                    try {
                        for (SnpFile f : bothFiles) {
                            updateProgress(prog++, total);
                            if (isCancelled()) {
                                return false;
                            }
                            List<SnpFile.SnpLine> lines = f.getSnpsInRegion(reg.getChromosome(),
                                    reg.getStartPos(), reg.getEndPos(), flanks);
                            for (SnpFile.SnpLine snpLine : lines) {
                                if (isCancelled()) {
                                    return false;
                                }
                                Integer coord = snpLine.getPosition();
                                if (!coordMap.containsKey(coord)) {
                                    coordMap.put(coord, new HashMap<String, String>());
                                }
                                String filename = f.inputFile.getName();
                                String rsId = snpLine.getId();
                                String call = snpLine.getCall();
                                coordMap.get(coord).put(filename, call);
                                coordToId.put(coord, rsId);
                            }
                        }
                        row = sheet.createRow(rowNo++);
                        Cell cell = row.createCell(0);
                        cell.setCellValue(reg.getCoordinateString());
                        row = sheet.createRow(rowNo++);
                        cell = row.createCell(0);
                        cell.setCellValue(reg.getIdLine());

                        int col = 0;
                        row = sheet.createRow(rowNo++);
                        cell = row.createCell(col++);
                        cell.setCellValue("Position");
                        cell = row.createCell(col++);
                        cell.setCellValue("rsID");
                        for (SnpFile f : bothFiles) {
                            updateProgress(prog++, total);
                            cell = row.createCell(col++);
                            if (f.getSampleName() != null && !f.getSampleName().isEmpty()) {
                                cell.setCellValue(f.getSampleName());
                            } else {
                                cell.setCellValue(f.inputFile.getName());
                            }
                        }
                        for (Entry current : coordMap.entrySet()) {
                            if (isCancelled()) {
                                return false;
                            }
                            col = 0;
                            Integer coord = (Integer) current.getKey();
                            row = sheet.createRow(rowNo++);
                            cell = row.createCell(col++);
                            cell.setCellValue(coord);
                            cell = row.createCell(col++);
                            cell.setCellValue(coordToId.get(coord));
                            HashMap<String, String> fileToCall = (HashMap<String, String>) current.getValue();
                            for (SnpFile f : bothFiles) {
                                cell = row.createCell(col++);
                                if (fileToCall.containsKey(f.inputFile.getName())) {
                                    cell.setCellValue(fileToCall.get(f.inputFile.getName()));
                                } else {
                                    cell.setCellValue("-");
                                }
                            }
                        }
                    } catch (Exception ex) {
                        return false;
                    }

                }
                CellRangeAddress[] regions = { new CellRangeAddress(0, rowNo, 2, 2 + bothFiles.size()) };
                SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

                ConditionalFormattingRule rule1 = sheetCF
                        .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AA\"");
                PatternFormatting fill1 = rule1.createPatternFormatting();
                fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
                fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                ConditionalFormattingRule rule2 = sheetCF
                        .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"BB\"");
                PatternFormatting fill2 = rule2.createPatternFormatting();
                fill2.setFillBackgroundColor(IndexedColors.PALE_BLUE.index);
                fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                ConditionalFormattingRule rule3 = sheetCF
                        .createConditionalFormattingRule(ComparisonOperator.EQUAL, "\"AB\"");
                PatternFormatting fill3 = rule3.createPatternFormatting();
                fill3.setFillBackgroundColor(IndexedColors.ROSE.index);
                fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
                sheetCF.addConditionalFormatting(regions, rule3, rule2);
                sheetCF.addConditionalFormatting(regions, rule1);
                wb.write(out);
                updateProgress(total, total);
                out.close();
            } catch (IOException | NumberFormatException ex) {
                ex.printStackTrace();
                return false;
            }
            return true;
        }
    };//end of task

    setProgressMode(true);
    progressBar.progressProperty().bind(writeTask.progressProperty());
    progressMessage.textProperty().bind(writeTask.messageProperty());
    writeTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            if (e.getSource().getValue() == true) {
                Dialogs.showInformationDialog(null,
                        "Saved regions written " + "to file " + "(" + regionFile.getName() + ")successfully",
                        "Regions Written", "SNP Viewer");
            } else {
                Dialogs.showErrorDialog(null, "Region write failed.", "Write Failed", "SNP Viewer");
            }
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("");

        }

    });
    writeTask.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            progressMessage.textProperty().unbind();
            progressMessage.setText("");
            progressTitle.setText("Region write failed!");
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer",
                    e.getSource().getException());

        }

    });
    writeTask.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            progressMessage.setText("Region write cancelled");
            progressTitle.setText("Cancelled");
            setProgressMode(false);
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().set(0);
            Dialogs.showErrorDialog(null, "Error writing region to file\n", "Region write error", "SNP Viewer");
        }

    });
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            writeTask.cancel();

        }
    });
    progressTitle.setText("Writing regions to .xlsx file");
    new Thread(writeTask).start();
}