Example usage for javax.swing JFileChooser setPreferredSize

List of usage examples for javax.swing JFileChooser setPreferredSize

Introduction

In this page you can find the example usage for javax.swing JFileChooser setPreferredSize.

Prototype

@BeanProperty(preferred = true, description = "The preferred size of the component.")
public void setPreferredSize(Dimension preferredSize) 

Source Link

Document

Sets the preferred size of this component.

Usage

From source file:com.mgmtp.jfunk.core.JFunk.java

private static List<File> requestScriptsViaGui() {
    final List<File> scripts = new ArrayList<>();

    try {//from   w w w .j a v  a2 s.co m
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser fileChooser = new JFileChooser(System.getProperty(JFunkConstants.USER_DIR));
                fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setPreferredSize(new Dimension(800, 450));
                int i = fileChooser.showOpenDialog(null);

                if (i == JFileChooser.APPROVE_OPTION) {
                    File[] files = fileChooser.getSelectedFiles();
                    scripts.addAll(Arrays.asList(files));
                }
            }
        });
    } catch (Exception e) {
        LOG.error("Error while requesting scripts via GUI", e);
    }

    return scripts;
}

From source file:com.mgmtp.jfunk.core.scripting.ScriptContext.java

/**
 * Opens a file chooser dialog which can then be used to choose a file or directory and assign
 * the path of the chosen object to a variable. The name of the variable must be passed as a
 * parameter.//from w w w .  ja va  2s .  c  o m
 * 
 * @param fileKey
 *            the key the selected file path is stored under in the configuration
 * @return the chosen file
 */
@Cmd
public File chooseFile(final String fileKey) {
    log.debug("Opening file chooser dialog");
    JFileChooser fileChooser = new JFileChooser(System.getProperty(JFunkConstants.USER_DIR));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileChooser.setPreferredSize(new Dimension(600, 326));
    int fileChooserResult = fileChooser.showOpenDialog(null);

    if (fileChooserResult == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        String filename = file.toString();
        log.info("Assigning file path '{}' to property '{}'", filename, fileKey);
        config.put(fileKey, filename);
        return file;
    }

    log.error("No file or directory was chosen, execution will abort");
    throw new IllegalArgumentException("No file or directory was chosen");
}

From source file:base.BasePlayer.AddGenome.java

@Override
public void mousePressed(MouseEvent e) {

    if (e.getSource() == tree) {

        if (selectedNode != null && selectedNode.toString().contains("Add new refe")) {
            try {
                FileDialog fs = new FileDialog(frame, "Select reference fasta-file", FileDialog.LOAD);
                fs.setDirectory(Main.downloadDir);
                fs.setVisible(true);/*from   w  ww  . j  a v a2s .  c  o m*/
                String filename = fs.getFile();
                fs.setFile("*.fasta;*.fa");
                fs.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.toLowerCase().contains(".fasta") || name.toLowerCase().contains(".fa");
                    }
                });
                if (filename != null) {
                    File addfile = new File(fs.getDirectory() + "/" + filename);

                    if (addfile.exists()) {

                        genomeFile = addfile;
                        Main.downloadDir = genomeFile.getParent();
                        Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                        OutputRunner runner = new OutputRunner(genomeFile.getName().replace(".fasta", "")
                                .replace(".fa", "").replace(".gz", ""), genomeFile, null);
                        runner.createGenome = true;
                        runner.execute();
                    } else {
                        Main.showError("File does not exists.", "Error", frame);
                    }

                }
                if (1 == 1) {
                    return;
                }
                JFileChooser chooser = new JFileChooser(Main.downloadDir);
                chooser.setMultiSelectionEnabled(false);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
                MyFilterFasta fastaFilter = new MyFilterFasta();

                chooser.addChoosableFileFilter(fastaFilter);
                chooser.setDialogTitle("Select reference fasta-file");
                if (Main.screenSize != null) {
                    chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                            (int) Main.screenSize.getHeight() / 3));
                }

                int returnVal = chooser.showOpenDialog((Component) this.getParent());

                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    genomeFile = chooser.getSelectedFile();
                    Main.downloadDir = genomeFile.getParent();
                    Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                    OutputRunner runner = new OutputRunner(
                            genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile, null);
                    runner.createGenome = true;
                    runner.execute();

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (selectedNode != null && selectedNode.isLeaf()
                && selectedNode.toString().contains("Add new anno")) {
            try {
                FileDialog fs = new FileDialog(frame, "Select annotation gff3/gtf-file", FileDialog.LOAD);
                fs.setDirectory(Main.downloadDir);
                fs.setVisible(true);
                String filename = fs.getFile();
                fs.setFile("*.gff3;*.gtf");
                fs.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.toLowerCase().contains(".gff3") || name.toLowerCase().contains(".gtf");
                    }
                });

                if (filename != null) {
                    File addfile = new File(fs.getDirectory() + "/" + filename);

                    if (addfile.exists()) {
                        annotationFile = addfile;
                        Main.downloadDir = annotationFile.getParent();
                        Main.writeToConfig("DownloadDir=" + annotationFile.getParent());
                        OutputRunner runner = new OutputRunner(selectedNode.getParent().toString(), null,
                                annotationFile);
                        runner.createGenome = true;
                        runner.execute();
                    } else {
                        Main.showError("File does not exists.", "Error", frame);
                    }

                }
                if (1 == 1) {
                    return;
                }
                JFileChooser chooser = new JFileChooser(Main.downloadDir);
                chooser.setMultiSelectionEnabled(false);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
                MyFilterGFF gffFilter = new MyFilterGFF();

                chooser.addChoosableFileFilter(gffFilter);
                chooser.setDialogTitle("Select annotation gff3-file");
                if (Main.screenSize != null) {
                    chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                            (int) Main.screenSize.getHeight() / 3));
                }
                int returnVal = chooser.showOpenDialog((Component) this.getParent());

                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    annotationFile = chooser.getSelectedFile();
                    Main.downloadDir = annotationFile.getParent();

                    Main.writeToConfig("DownloadDir=" + annotationFile.getParent());
                    OutputRunner runner = new OutputRunner(selectedNode.getParent().toString(), null,
                            annotationFile);
                    runner.createGenome = true;
                    runner.execute();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    if (e.getSource() == genometable) {

        if (new File(".").getFreeSpace()
                / 1048576 < sizeHash.get(genometable.getValueAt(genometable.getSelectedRow(), 0))[0]
                        / 1048576) {
            sizeError.setVisible(true);
            download.setEnabled(false);
            AddGenome.getLinks.setEnabled(false);
        } else {
            sizeError.setVisible(false);
            download.setEnabled(true);
            AddGenome.getLinks.setEnabled(true);
        }
        tree.clearSelection();
        remove.setEnabled(false);
        checkUpdates.setEnabled(false);
    }

}

From source file:base.BasePlayer.AddGenome.java

public void actionPerformed(ActionEvent event) {
    if (event.getSource() == download) {
        if (!downloading) {
            downloading = true;//from  w w w. j  ava2 s . c om
            downloadGenome(genometable.getValueAt(genometable.getSelectedRow(), 0).toString());
            downloading = false;
        }
    } else if (event.getSource() == getLinks) {
        URL[] urls = AddGenome.genomeHash
                .get(genometable.getValueAt(genometable.getSelectedRow(), 0).toString());
        JPopupMenu menu = new JPopupMenu();
        JTextArea area = new JTextArea();
        JScrollPane menuscroll = new JScrollPane();
        area.setFont(Main.menuFont);
        menu.add(menuscroll);
        menu.setPreferredSize(new Dimension(
                menu.getFontMetrics(Main.menuFont).stringWidth(urls[0].toString()) + Main.defaultFontSize * 10,
                (int) menu.getFontMetrics(Main.menuFont).getHeight() * 4));
        //area.setMaximumSize(new Dimension(300, 600));
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        for (int i = 0; i < urls.length; i++) {
            area.append(urls[i].toString() + "\n");
        }

        area.setCaretPosition(0);
        area.revalidate();
        menuscroll.getViewport().add(area);
        menu.pack();
        menu.show(this, 0, 0);

    } else if (event.getSource() == checkEnsembl) {
        if (ensemblfetch) {
            menu.show(AddGenome.treescroll, 0, 0);
        } else {
            EnsemblFetch fetcher = new EnsemblFetch();
            fetcher.execute();
        }
    } else if (event.getSource() == checkUpdates) {
        URL testfile = null;
        try {
            // kattoo onko paivityksia annotaatioon
            String ref = selectedNode.toString();
            if (AddGenome.genomeHash.get(ref) != null) {
                ArrayList<String> testfiles = new ArrayList<String>();
                if (Main.drawCanvas != null) {
                    for (int i = 0; i < Main.genomehash.get(ref).size(); i++) {
                        testfiles.add(Main.genomehash.get(ref).get(i).getName().replace(".bed.gz", ""));
                    }
                }
                testfile = AddGenome.genomeHash.get(ref)[1];
                String result = Main.checkFile(testfile, testfiles);

                if (result.length() == 0) {
                    Main.showError("You have newest annotation file.", "Note");
                } else {
                    int n = JOptionPane.showConfirmDialog(Main.drawCanvas,
                            "New annotation file found: " + result + "\nDownload it now?", "Note",
                            JOptionPane.YES_NO_OPTION);
                    if (n == JOptionPane.YES_OPTION) {
                        URL fileurl = new URL(testfile.getProtocol() + "://" + testfile.getHost()
                                + testfile.getPath().substring(0, testfile.getPath().lastIndexOf("/") + 1)
                                + result);
                        OutputRunner runner = new OutputRunner(fileurl, ref);
                        runner.downloadAnnotation = true;
                        runner.execute();
                    }
                }
            } else {
                Main.showError("This genome is not from Ensembl list, could not check for updates.", "Note",
                        AddGenome.genometable);
            }
        } catch (Exception e) {
            Main.showError("Cannot connect to " + testfile.getHost() + ".\nTry again later.", "Error");
            e.printStackTrace();
        }
    } else if (event.getSource() == remove) {
        if (!selectedNode.isLeaf()) {
            String removeref = selectedNode.toString();
            //   Boolean same = false;
            try {
                if (Main.drawCanvas != null) {
                    if (removeref.equals(Main.refDropdown.getSelectedItem().toString())) {
                        Main.referenceFile.close();
                        //      same = true;
                        if (ChromDraw.exonReader != null) {
                            ChromDraw.exonReader.close();
                        }
                    }
                }
                if (Main.genomehash.containsKey(removeref)) {
                    for (int i = Main.genomehash.get(removeref).size() - 1; i >= 0; i--) {
                        Main.genomehash.get(removeref).remove(i);
                    }
                    Main.genomehash.remove(removeref);

                }
                if (Main.drawCanvas != null) {
                    Main.refModel.removeElement(removeref);
                    Main.refDropdown.removeItem(removeref);
                    Main.refDropdown.revalidate();
                }

                for (int i = 0; i < Main.genome.getItemCount(); i++) {
                    if (Main.genome.getItem(i).getName() != null) {

                        if (Main.genome.getItem(i).getName().equals(removeref)) {
                            Main.genome.remove(Main.genome.getItem(i));
                            break;
                        }
                    }
                }

                FileUtils.deleteDirectory(new File(Main.genomeDir.getCanonicalPath() + "/" + removeref));
                checkGenomes();
                Main.setAnnotationDrop("");

                if (Main.genomehash.size() == 0) {
                    Main.refDropdown.setSelectedIndex(0);
                    Main.setChromDrop("-1");
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Main.showError("Could not delete genome folder.\nYou can do it manually by deleting folder "
                            + Main.genomeDir.getCanonicalPath() + "/" + removeref, "Note");
                } catch (IOException e1) {

                    e1.printStackTrace();
                }
            }
        } else {
            try {
                if (Main.drawCanvas != null) {
                    if (ChromDraw.exonReader != null) {
                        ChromDraw.exonReader.close();
                    }
                }

                Main.removeAnnotationFile(selectedNode.getParent().toString(), selectedNode.toString());

                FileUtils.deleteDirectory(new File(Main.genomeDir.getCanonicalPath() + "/"
                        + selectedNode.getParent().toString() + "/annotation/" + selectedNode.toString()));

                //   root.remove(selectedNode.getParent().getIndex(selectedNode));
                //   root.remove
                //   checkGenomes();

            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Main.showError("Could not delete genome folder.\nYou can do it manually by deleting folder "
                            + Main.genomeDir.getCanonicalPath() + "/" + selectedNode.getParent().toString()
                            + "/annotation/" + selectedNode.toString(), "Note");
                } catch (IOException e1) {

                    e1.printStackTrace();
                }
            }
            treemodel.removeNodeFromParent(selectedNode);
        }

    } else if (event.getSource() == add) {

        if (genomeFile == null) {
            if (new File(genomeFileText.getText()).exists()) {
                genomeFile = new File(genomeFileText.getText());

            } else {
                genomeFileText.setText("Select reference genome fasta-file.");
                genomeFileText.setForeground(Color.red);
                return;
            }
        }

        /*if(genomeName.getText().contains("Give name") || genomeName.getText().length() == 0) {
           genomeName.setText("Give name of the genome");
           genomeName.setForeground(Color.red);
           genomeName.revalidate();
                   
        }
        else if(!annotation && new File(Main.userDir +"/genomes/"+genomeName.getText().trim().replace("\\s+", "_")).exists()) {
           genomeName.setText("This genome exists already.");
           genomeName.setForeground(Color.red);
           genomeName.revalidate();
        }
        else */

        if ((genomeFileText.getText().length() == 0
                || genomeFileText.getText().startsWith("Select reference"))) {
            genomeFileText.setText("Select reference genome fasta-file.");
            genomeFileText.setForeground(Color.red);
            genomeFileText.revalidate();
        }

        else {

            OutputRunner runner = new OutputRunner(
                    genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile, annotationFile);
            runner.execute();
        }

    } else if (event.getSource() == openRef) {
        try {

            JFileChooser chooser = new JFileChooser(Main.downloadDir);
            chooser.setMultiSelectionEnabled(false);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);
            MyFilterFasta fastaFilter = new MyFilterFasta();

            chooser.addChoosableFileFilter(fastaFilter);
            chooser.setDialogTitle("Select reference fasta-file");
            if (Main.screenSize != null) {
                chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                        (int) Main.screenSize.getHeight() / 3));
            }

            int returnVal = chooser.showOpenDialog((Component) this.getParent());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                genomeFile = chooser.getSelectedFile();
                Main.downloadDir = genomeFile.getParent();
                Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                genomeFileText.setText(genomeFile.getName());
                genomeFileText.revalidate();
                frame.pack();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else if (event.getSource() == openAnno) {
        try {

            JFileChooser chooser = new JFileChooser(Main.downloadDir);
            chooser.setMultiSelectionEnabled(false);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);
            MyFilterGFF gffFilter = new MyFilterGFF();

            chooser.addChoosableFileFilter(gffFilter);
            chooser.setDialogTitle("Select annotation gff3-file");
            if (Main.screenSize != null) {
                chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                        (int) Main.screenSize.getHeight() / 3));
            }
            int returnVal = chooser.showOpenDialog((Component) this.getParent());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                if (genomeFile == null) {
                    genomeFile = Main.fastahash.get(Main.hoverGenome);
                }
                annotationFile = chooser.getSelectedFile();
                Main.downloadDir = annotationFile.getParent();
                Main.writeToConfig("DownloadDir=" + annotationFile.getParent());

                OutputRunner runner = new OutputRunner(
                        genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile,
                        annotationFile);
                runner.execute();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:base.BasePlayer.Main.java

public void actionPerformed(ActionEvent e) {
    //Logo.frame.setVisible(false);
    if (e.getSource() == pleiadesButton) {
        gotoURL("http://kaptah.local.lab.helsinki.fi/pleiades/");

    } else if (e.getSource() == manage) {

        if (VariantHandler.frame == null) {
            VariantHandler.main(argsit);
        }//from   w w w  . j  ava  2s  . com
        VariantHandler.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - VariantHandler.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);

        VariantHandler.frame.setState(JFrame.NORMAL);
        VariantHandler.frame.setVisible(true);
        Draw.calculateVars = true;
        Draw.updatevars = true;
        drawCanvas.repaint();

    } else if (e.getSource() == tbrowser) {
        tablebrowser.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - VariantCaller.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);
        tablebrowser.frame.setState(JFrame.NORMAL);

        tablebrowser.frame.setVisible(true);
    } else if (e.getSource() == bconvert) {
        bedconverter.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - VariantCaller.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);
        bedconverter.frame.setState(JFrame.NORMAL);

        bedconverter.frame.setVisible(true);
    } else if (e.getSource() == peakCaller) {
        if (PeakCaller.frame == null) {

            PeakCaller.main(argsit);

        }
        PeakCaller.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - VariantCaller.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);
        PeakCaller.frame.setState(JFrame.NORMAL);
        PeakCaller.frame.setVisible(true);
    } else if (e.getSource() == variantCaller) {

        //FileRead.checkSamples();

        if (VariantCaller.frame == null) {

            VariantCaller.main(argsit);

        }
        VariantCaller.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - VariantCaller.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);
        VariantCaller.frame.setState(JFrame.NORMAL);
        VariantCaller.frame.setVisible(true);
    } else if (e.getSource() == average) {
        if (Average.frame == null) {
            Average.createAndShowGUI();
        }
        Average.setSamples();

        Average.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - Average.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);

        Average.frame.setState(JFrame.NORMAL);
        Average.frame.setVisible(true);
    } else if (e.getSource() == errorlog) {

        ErrorLog.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - ErrorLog.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);

        //      VariantHandler.frame.setAlwaysOnTop(true);   
        ErrorLog.frame.setState(JFrame.NORMAL);
        ErrorLog.frame.setVisible(true);

    }
    /*   else if(e.getSource() == help) {
          JOptionPane.showMessageDialog(Main.chromDraw, "This is pre-release version of BasePlayer\nContact: help@baseplayer.fi\nUniversity of Helsinki", "Help", JOptionPane.INFORMATION_MESSAGE);
       }*/
    else if (e.getSource() == settings) {

        Settings.frame.setLocation(
                frame.getLocationOnScreen().x + frame.getWidth() / 2 - Settings.frame.getWidth() / 2,
                frame.getLocationOnScreen().y + frame.getHeight() / 6);

        Settings.frame.setState(JFrame.NORMAL);
        Settings.frame.setVisible(true);
    } else if (e.getSource() == update) {
        try {
            Updater update = new Updater();
            update.execute();

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

    } else if (e.getSource() == clearMemory) {
        FileRead.nullifyVarNodes();

        //FileRead.removeNonListVariants();f
        System.gc();
        chromDraw.repaint();
    } else if (e.getSource() == zoomout) {

        zoomout();
    } else if (e.getSource() == dosomething) {

        BedNode currentbed = bedCanvas.bedTrack.get(0).getHead().getNext();
        VarNode currentvar = FileRead.head.getNext();

        while (currentbed != null) {

            while (currentvar != null && currentvar.getPosition() < currentbed.getPosition()) {
                currentvar = currentvar.getNext();
            }
            while (currentbed != null
                    && currentvar.getPosition() > currentbed.getPosition() + currentbed.getLength()) {
                currentbed = currentbed.getNext();
            }

            if (currentvar != null && currentvar.getPosition() >= currentbed.getPosition()
                    && currentvar.getPosition() < currentbed.getPosition() + currentbed.getLength()) {
                currentvar.setBedhit(true);
                currentvar = currentvar.getNext();
            }
            if (currentvar == null) {
                break;
            }
            currentbed = currentbed.getNext();
        }

    } else if (e.getSource() == clear) {
        clearData();
    } else if (e.getSource() == exit) {

        System.exit(0);
    } else if (e.getSource() == openbams) {
        try {
            if (!checkGenome())
                return;
            if (VariantHandler.frame != null) {
                VariantHandler.frame.setState(Frame.ICONIFIED);
            }

            FileDialog fc = new FileDialog(frame, "Choose BAM file(s)", FileDialog.LOAD);
            fc.setDirectory(path);
            fc.setFile("*.bam;*.cram;*.link");
            fc.setFilenameFilter(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".bam") || name.toLowerCase().endsWith(".cram")
                            || name.toLowerCase().endsWith(".link");
                }
            });
            fc.setMultipleMode(true);
            fc.setVisible(true);
            File[] openfiles = fc.getFiles();

            if (openfiles != null && openfiles.length > 0) {

                path = openfiles[0].getParent();
                writeToConfig("DefaultDir=" + path);
                FileRead filereader = new FileRead(openfiles);

                filereader.start = (int) drawCanvas.selectedSplit.start;
                filereader.end = (int) drawCanvas.selectedSplit.end;
                filereader.readBAM = true;
                filereader.execute();

            } else {
                //Main.showError("File(s) does not exist.", "Error");
            }

        } catch (Exception ex) {
            Main.showError(ex.getMessage(), "Error");
        }
    } else if (e.getSource() == openvcfs) {
        try {
            if (!checkGenome())
                return;
            if (VariantHandler.frame != null) {
                VariantHandler.frame.setState(Frame.ICONIFIED);
            }

            FileDialog fc = new FileDialog(frame, "Choose VCF file(s)", FileDialog.LOAD);
            fc.setDirectory(path);
            fc.setFile("*.vcf");
            fc.setFilenameFilter(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".vcf") || name.toLowerCase().endsWith(".vcf.gz");
                }
            });

            fc.setMultipleMode(true);
            fc.setVisible(true);
            File[] openfiles = fc.getFiles();

            if (openfiles != null && openfiles.length > 0) {

                path = openfiles[0].getParent();
                writeToConfig("DefaultDir=" + path);
                FileRead filereader = new FileRead(openfiles);

                filereader.start = (int) drawCanvas.selectedSplit.start;
                filereader.end = (int) drawCanvas.selectedSplit.end;
                filereader.readVCF = true;
                filereader.execute();

            } else {
                //Main.showError("File(s) does not exist.", "Error");
            }

            if (1 == 1) {
                return;
            }

            JFileChooser chooser = new JFileChooser(path);
            getText(chooser.getComponents());
            chooser.setMultiSelectionEnabled(true);
            //chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.addChoosableFileFilter(vcfFilter);
            chooser.addChoosableFileFilter(bamFilter);
            chooser.addChoosableFileFilter(linkFilter);
            if (defaultSelectType == "vcf") {
                chooser.setFileFilter(vcfFilter);
            } else if (defaultSelectType == "bam") {
                chooser.setFileFilter(bamFilter);
            } else {
                chooser.setFileFilter(linkFilter);
            }
            chooser.setDialogTitle("Add samples");
            chooser.setPreferredSize(
                    new Dimension((int) screenSize.getWidth() / 3, (int) screenSize.getHeight() / 3));
            int returnVal = chooser.showOpenDialog((Component) this.getParent());

            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File vcffiles[] = chooser.getSelectedFiles();
                if (vcffiles.length == 1 && !vcffiles[0].exists() && pleiades) {

                    if (Main.chooserText.contains("`")) {
                        Main.chooserText.replace("`", "?");
                    }
                    if (Main.chooserText.contains(" ")) {
                        Main.chooserText.replace(" ", "%20");
                    }
                    if (Main.chooserText.contains("pleiades")) {
                        try {
                            URL url = new URL(Main.chooserText);
                            //System.out.println(Main.chooserText);
                            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                            httpConn.connect();

                            int responseCode = httpConn.getResponseCode();

                            if (responseCode == HttpsURLConnection.HTTP_OK) {

                                String loading = drawCanvas.loadingtext;
                                InputStream inputStream = httpConn.getInputStream();
                                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                                Main.drawCanvas.loadingtext = loading + " 0MB";
                                String line;
                                StringBuffer buffer = new StringBuffer("");
                                while ((line = reader.readLine()) != null) {

                                    buffer.append(line);

                                }
                                inputStream.close();
                                reader.close();
                                String split2;
                                String[] split = buffer.toString().split("dataUnit");
                                String location;
                                ArrayList<File> array = new ArrayList<File>();
                                File[] paths;
                                FileSystemView fsv = FileSystemView.getFileSystemView();
                                paths = File.listRoots();
                                String loc = "/mnt";
                                boolean missingfiles = false;
                                for (File path : paths) {
                                    if (fsv.getSystemDisplayName(path).contains("merit")) {
                                        loc = path.getCanonicalPath();
                                    }
                                }

                                for (int i = 0; i < split.length; i++) {

                                    if (!split[i].contains("lastLocation")) {

                                        continue;
                                    }

                                    split2 = split[i].split("\"lastLocation\":\"")[1];
                                    location = split2.substring(0, split2.indexOf("\"}"));
                                    String filename = "";
                                    String testloc = location.replace("/mnt", loc) + "/wgspipeline/";
                                    File testDir = new File(testloc);
                                    if (testDir.exists() && testDir.isDirectory()) {
                                        if (chooser.getFileFilter()
                                                .equals(chooser.getChoosableFileFilters()[1])) {
                                            File[] addDir = testDir.listFiles(new FilenameFilter() {
                                                public boolean accept(File dir, String name) {
                                                    return name.toLowerCase().endsWith(".bam")
                                                            || name.toLowerCase().endsWith(".cram");
                                                }
                                            });
                                            if (addDir.length > 0) {
                                                filename = addDir[0].getName();
                                            }
                                        } else {
                                            File[] addDir = testDir.listFiles(new FilenameFilter() {
                                                public boolean accept(File dir, String name) {
                                                    return name.toLowerCase().endsWith(".vcf.gz");
                                                }
                                            });
                                            if (addDir.length > 0) {
                                                filename = addDir[0].getName();
                                            }
                                        }
                                    }

                                    location = testloc + "/" + filename;

                                    if (!new File(location).exists()) {

                                        if (!new File(location).exists()) {
                                            missingfiles = true;
                                            ErrorLog.addError("No sample files found in " + testloc);

                                        } else {
                                            array.add(new File(location));
                                        }
                                    } else {

                                        array.add(new File(location));
                                    }
                                }

                                File[] files = new File[array.size()];
                                for (int i = 0; i < files.length; i++) {

                                    files[i] = array.get(i);
                                }
                                FileRead filereader = new FileRead(files);
                                filereader.start = (int) drawCanvas.selectedSplit.start;
                                filereader.end = (int) drawCanvas.selectedSplit.end;
                                if (chooser.getFileFilter().equals(chooser.getChoosableFileFilters()[1])) {
                                    filereader.readBAM = true;
                                } else {
                                    filereader.readVCF = true;
                                }
                                filereader.execute();
                                if (missingfiles) {
                                    JOptionPane.showMessageDialog(Main.drawScroll,
                                            "Missing files. Check Tools->View log", "Note",
                                            JOptionPane.INFORMATION_MESSAGE);
                                }

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

                    return;
                }

                if (vcffiles.length > 0) {
                    path = vcffiles[0].getParent();
                    writeToConfig("DefaultDir=" + path);
                    FileRead filereader = new FileRead(vcffiles);

                    if (chooser.getFileFilter().equals(chooser.getChoosableFileFilters()[0])) {
                        defaultSelectType = "vcf";
                        filereader.start = (int) drawCanvas.selectedSplit.start;
                        filereader.end = (int) drawCanvas.selectedSplit.end;
                        filereader.readVCF = true;
                        filereader.execute();
                    } else if (chooser.getFileFilter().equals(chooser.getChoosableFileFilters()[1])) {
                        defaultSelectType = "bam";
                        filereader.readBAM = true;
                        filereader.execute();
                    } else if (chooser.getFileFilter().equals(chooser.getChoosableFileFilters()[2])) {

                        defaultSelectType = "link";
                        filereader.readBAM = true;
                        filereader.execute();
                    }
                } else {

                    JOptionPane.showMessageDialog(Main.drawScroll,
                            "The file does not exist. The file link may be broken.\nThe problem may also be the Java run time version in Linux.",
                            "Note", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    } else if (e.getSource() == addcontrols) {
        if (!checkGenome())
            return;
        if (VariantHandler.frame != null) {
            VariantHandler.frame.setState(Frame.ICONIFIED);
        }
        FileDialog fc = new FileDialog(frame, "Choose control file(s)", FileDialog.LOAD);
        fc.setDirectory(Main.controlDir);
        fc.setFile("*.vcf.gz");
        fc.setFilenameFilter(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".vcf.gz");
            }
        });
        fc.setMultipleMode(true);
        fc.setVisible(true);
        File[] openfiles = fc.getFiles();

        if (openfiles != null && openfiles.length > 0) {

            controlDir = openfiles[0].getParent();
            writeToConfig("DefaultControlDir=" + controlDir);

            Control.addFiles(openfiles);
        }
        if (1 == 1) {
            return;
        }
        JFileChooser chooser = new JFileChooser(controlDir);
        //        JFileChooser chooser = new JFileChooser(path);            
        chooser.setMultiSelectionEnabled(true);
        chooser.setAcceptAllFileFilterUsed(false);
        Control.MyFilter vcfFilter = new Control.MyFilter();
        chooser.addChoosableFileFilter(vcfFilter);

        chooser.setDialogTitle("Add controls");
        chooser.setPreferredSize(
                new Dimension((int) screenSize.getWidth() / 3, (int) screenSize.getHeight() / 3));
        int returnVal = chooser.showOpenDialog((Component) this.getParent());

        if (returnVal == JFileChooser.APPROVE_OPTION) {

            File vcffiles[] = chooser.getSelectedFiles();
            controlDir = vcffiles[0].getParent();
            writeToConfig("DefaultControlDir=" + controlDir);

            if (chooser.getFileFilter().equals(chooser.getChoosableFileFilters()[0])) {
                Control.addFiles(vcffiles);
            }
        }
    } else if (e.getSource() == addtracks) {
        if (!checkGenome())
            return;
        try {
            if (!checkGenome())
                return;
            if (VariantHandler.frame != null) {
                VariantHandler.frame.setState(Frame.ICONIFIED);
            }

            FileDialog fc = new FileDialog(frame, "Choose track file(s)", FileDialog.LOAD);
            fc.setDirectory(Main.trackDir);
            fc.setFile(
                    "*.bed;*.bedgraph.gz;*.gff.gz;*.gff3.gz;*.bigwig;*.bw;*.bigbed;*.bb;*.tsv.gz;*.tsv.bgz;*.txt");
            fc.setFilenameFilter(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".bed") || name.toLowerCase().endsWith(".bed.gz")
                            || name.toLowerCase().endsWith(".bedgraph.gz")
                            || name.toLowerCase().endsWith(".bedgraph.gz")
                            || name.toLowerCase().endsWith(".bedgraph.gz")
                            || name.toLowerCase().endsWith(".gff.gz") || name.toLowerCase().endsWith(".gff3.gz")
                            || name.toLowerCase().endsWith(".bigwig") || name.toLowerCase().endsWith(".bw")
                            || name.toLowerCase().endsWith(".bigbed") || name.toLowerCase().endsWith(".bb")
                            || name.toLowerCase().endsWith(".tsv.gz") || name.toLowerCase().endsWith(".tsv.bgz")
                            || name.toLowerCase().endsWith(".txt");
                }
            });
            fc.setMultipleMode(true);
            fc.setVisible(true);
            File[] openfiles = fc.getFiles();

            if (openfiles != null && openfiles.length > 0) {

                trackDir = openfiles[0].getParent();
                writeToConfig("DefaultTrackDir=" + trackDir);
                FileRead filereader = new FileRead(openfiles);
                filereader.readBED = true;
                filereader.execute();

            } else {
                //Main.showError("File(s) does not exist.", "Error");
            }

        } catch (Exception ex) {
            Main.showError(ex.getMessage(), "Error");
        }
        if (1 == 1) {
            return;
        }
        if (VariantHandler.frame != null) {
            VariantHandler.frame.setState(Frame.ICONIFIED);
        }
        JFileChooser chooser = new JFileChooser(Main.trackDir);
        getText(chooser.getComponents());
        chooser.setMultiSelectionEnabled(true);
        chooser.setAcceptAllFileFilterUsed(false);
        MyFilterBED bedFilter = new MyFilterBED();
        MyFilterTXT txtFilter = new MyFilterTXT();
        chooser.addChoosableFileFilter(bedFilter);
        chooser.addChoosableFileFilter(txtFilter);
        chooser.setDialogTitle("Add tracks");
        chooser.setPreferredSize(
                new Dimension((int) screenSize.getWidth() / 3, (int) screenSize.getHeight() / 3));
        int returnVal = chooser.showOpenDialog((Component) this.getParent());

        try {

            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File bedfiles[] = chooser.getSelectedFiles();
                if (bedfiles[0].exists()) {

                    trackDir = bedfiles[0].getParent();
                    writeToConfig("DefaultTrackDir=" + trackDir);
                    FileRead filereader = new FileRead(bedfiles);
                    filereader.readBED(bedfiles);

                } else {

                    if (Main.chooserText.length() > 5 && Main.chooserText.endsWith(".bed.gz")
                            || Main.chooserText.endsWith(".gff.gz") || Main.chooserText.endsWith(".gff3.gz")
                            || Main.chooserText.endsWith(".bedgraph.gz")) {

                        if (Main.chooserText.startsWith("http://") || Main.chooserText.startsWith("ftp://")) {

                            URL url = new URL(Main.chooserText);
                            SeekableStream stream = SeekableStreamFactory.getInstance().getStreamFor(url);
                            TabixReader tabixReader = null;
                            String index = null;

                            try {
                                tabixReader = new TabixReader(Main.chooserText, Main.chooserText + ".tbi",
                                        stream);
                                index = Main.chooserText + ".tbi";
                            } catch (Exception ex) {
                                try {
                                    tabixReader = new TabixReader(Main.chooserText,
                                            Main.chooserText.substring(0, Main.chooserText.indexOf(".gz"))
                                                    + ".tbi",
                                            stream);
                                    index = Main.chooserText.substring(0, Main.chooserText.indexOf(".gz"))
                                            + ".tbi";
                                } catch (Exception exc) {
                                    exc.printStackTrace();
                                }
                            }
                            if (tabixReader != null && index != null) {

                                FileRead filereader = new FileRead(bedfiles);
                                filereader.readBED(Main.chooserText, index, false);

                                tabixReader.close();
                            }
                        }
                    } else {
                        if (Main.chooserText.contains("://")) {

                            try {
                                //        bbreader = new BBFileReader(Main.chooserText, stream);

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

                            //  if(bbreader != null) {

                            FileRead filereader = new FileRead(bedfiles);
                            filereader.readBED(Main.chooserText, "nan", false);

                            //     }
                            //     stream.close();
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else if (e.getSource() == openProject) {
        if (!checkGenome())
            return;
        if (VariantHandler.frame != null) {
            VariantHandler.frame.setState(Frame.ICONIFIED);
        }
        openProject();
    } else if (e.getSource() == saveProjectAs) {
        if (VariantHandler.frame != null) {
            VariantHandler.frame.setState(Frame.ICONIFIED);
        }
        try {
            File savefile = null;
            FileDialog fs = new FileDialog(frame, "Save project as...", FileDialog.SAVE);
            fs.setDirectory(projectDir);
            fs.setFile("*.ses");
            fs.setFilenameFilter(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".ses");
                }
            });
            fs.setVisible(true);

            while (true) {
                String filename = fs.getFile();

                if (filename != null) {
                    savefile = new File(fs.getDirectory() + "/" + filename);
                    projectDir = fs.getDirectory();
                    writeToConfig("DefaultProjectDir=" + projectDir);

                    /* if(!Files.isWritable(Paths.get(savefile.getParent()))) {
                       Main.showError("No permission to write.", "Error");
                       continue;
                     }*/

                    if (!savefile.getAbsolutePath().endsWith(".ses")) {
                        savefile = new File(savefile.getAbsolutePath() + ".ses");
                    }

                    Serializer ser = new Serializer();
                    ser.serialize(savefile);
                    break;
                } else {
                    break;
                }
            }
            if (1 == 1) {
                return;
            }
            JFileChooser chooser = new JFileChooser();
            chooser.setAcceptAllFileFilterUsed(false);
            MyFilterSES sesFilter = new MyFilterSES();
            chooser.addChoosableFileFilter(sesFilter);
            chooser.setDialogTitle("Save project as...");
            int returnVal = chooser.showSaveDialog((Component) this.getParent());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File outfile = chooser.getSelectedFile();
                if (!outfile.getAbsolutePath().endsWith(".ses")) {
                    outfile = new File(outfile.getAbsolutePath() + ".ses");
                }

                Serializer ser = new Serializer();
                ser.serialize(outfile);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    } else if (e.getSource() == saveProject) {
        if (drawCanvas.drawVariables.projectName.equals("Untitled")) {
            saveProjectAs.doClick();
        } else {

            Serializer ser = new Serializer();
            ser.serialize(drawCanvas.drawVariables.projectFile);
        }
    }
    /*      else if(e.getSource() == welcome) {
             WelcomeScreen.main(args);
             WelcomeScreen.frame.setVisible(true);
             WelcomeScreen.frame.setLocation(frame.getLocationOnScreen().x+frame.getWidth()/2 - WelcomeScreen.frame.getWidth()/2, frame.getLocationOnScreen().y+frame.getHeight()/6);
                     
          }*/
}

From source file:processing.app.Base.java

public void handleAddLibrary() {
    JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home"));
    fileChooser.setDialogTitle(tr("Select a zip file or a folder containing the library you'd like to add"));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    fileChooser.setFileFilter(new FileNameExtensionFilter(tr("ZIP files or folders"), "zip"));

    Dimension preferredSize = fileChooser.getPreferredSize();
    fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200));

    int returnVal = fileChooser.showOpenDialog(activeEditor);

    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return;/*from  www .  j av a 2 s.c  o m*/
    }

    File sourceFile = fileChooser.getSelectedFile();
    File tmpFolder = null;

    try {
        // unpack ZIP
        if (!sourceFile.isDirectory()) {
            try {
                tmpFolder = FileUtils.createTempFolder();
                ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder);
                zipDeflater.deflate();
                File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs());
                if (foldersInTmpFolder.length != 1) {
                    throw new IOException(tr("Zip doesn't contain a library"));
                }
                sourceFile = foldersInTmpFolder[0];
            } catch (IOException e) {
                activeEditor.statusError(e);
                return;
            }
        }

        File libFolder = sourceFile;
        if (FileUtils.isSubDirectory(new File(PreferencesData.get("sketchbook.path")), libFolder)) {
            activeEditor.statusError(tr("A subfolder of your sketchbook is not a valid library"));
            return;
        }

        if (FileUtils.isSubDirectory(libFolder, new File(PreferencesData.get("sketchbook.path")))) {
            activeEditor.statusError(tr("You can't import a folder that contains your sketchbook"));
            return;
        }

        String libName = libFolder.getName();
        if (!BaseNoGui.isSanitaryName(libName)) {
            String mess = I18n.format(tr("The library \"{0}\" cannot be used.\n"
                    + "Library names must contain only basic letters and numbers.\n"
                    + "(ASCII only and no spaces, and it cannot start with a number)"), libName);
            activeEditor.statusError(mess);
            return;
        }

        String[] headers;
        File libProp = new File(libFolder, "library.properties");
        File srcFolder = new File(libFolder, "src");
        if (libProp.exists() && srcFolder.isDirectory()) {
            headers = BaseNoGui.headerListFromIncludePath(srcFolder);
        } else {
            headers = BaseNoGui.headerListFromIncludePath(libFolder);
        }
        if (headers.length == 0) {
            activeEditor.statusError(tr("Specified folder/zip file does not contain a valid library"));
            return;
        }

        // copy folder
        File destinationFolder = new File(BaseNoGui.getSketchbookLibrariesFolder().folder,
                sourceFile.getName());
        if (!destinationFolder.mkdir()) {
            activeEditor
                    .statusError(I18n.format(tr("A library named {0} already exists"), sourceFile.getName()));
            return;
        }
        try {
            FileUtils.copy(sourceFile, destinationFolder);
        } catch (IOException e) {
            activeEditor.statusError(e);
            return;
        }
        activeEditor.statusNotice(tr("Library added to your libraries. Check \"Include library\" menu"));
    } catch (IOException e) {
        // FIXME error when importing. ignoring :(
    } finally {
        // delete zip created temp folder, if exists
        newLibraryImported = true;
        FileUtils.recursiveDelete(tmpFolder);
    }
}

From source file:ui.FtpDialog.java

private void uploadFileBtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadFileBtActionPerformed

    if (connected) {
        JFileChooser uploadFileChooser = new JFileChooser();
        uploadFileChooser.setPreferredSize(new Dimension(650, 450));

        File rootDirectory = new File("C:\\");

        uploadFileChooser/*  w w w  .j av a 2 s. com*/
                .setCurrentDirectory(uploadFileChooser.getFileSystemView().getParentDirectory(rootDirectory));

        uploadFileChooser.setDialogTitle("File to upload");
        int result = uploadFileChooser.showOpenDialog(this);
        switch (result) {

        case JFileChooser.APPROVE_OPTION:
            selectedFile = uploadFileChooser.getSelectedFile();

            Trace.trc("File to upload: " + selectedFile.getName() + " File size: "
                    + FileUtils.byteCountToDisplaySize(selectedFile.length()));

            if (connected) {
                if (!selectedFile.equals(null)) {
                    try {
                        input = new FileInputStream(selectedFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    pb = new ProgressBar();
                    pb.execute();

                    uploadFileChooser.setVisible(false);

                } else {
                    JOptionPane.showMessageDialog(rootFrame, "No file to upload has been chosen!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(rootFrame, "Not connected to a server, cannot upload file!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
            break;

        case JFileChooser.CANCEL_OPTION:
            Trace.trc("Closing file chooser dialog");
            break;

        case JFileChooser.ERROR_OPTION:
            Trace.trc("An error occured");
            break;
        }

    } else {
        JOptionPane.showMessageDialog(rootFrame, "Not connected to a server, cannot upload file!", "Error",
                JOptionPane.ERROR_MESSAGE);
    }

}