Example usage for java.awt FileDialog setDirectory

List of usage examples for java.awt FileDialog setDirectory

Introduction

In this page you can find the example usage for java.awt FileDialog setDirectory.

Prototype

public void setDirectory(String dir) 

Source Link

Document

Sets the directory of this file dialog window to be the specified directory.

Usage

From source file:edu.ku.brc.specify.tasks.QueryTask.java

/**
 * //  ww w  .j  a v a 2 s .  c  o m
 */
protected void exportQueries() {
    UsageTracker.incrUsageCount(getExportUsageKey());
    Vector<String> list = new Vector<String>();
    for (NavBoxItemIFace nbi : navBox.getItems()) {
        list.add(nbi.getTitle());
    }

    List<String> selectedList = null;
    if (list.size() == 0) {
        UIRegistry.showLocalizedMsg(getNothingToExporti18nKey());
        return;
    }
    if (list.size() == 1) {
        selectedList = list;
    } else {
        ToggleButtonChooserDlg<String> dlg = new ToggleButtonChooserDlg<String>(
                (Frame) UIRegistry.getMostRecentWindow(), getExportDlgTitlei18nKey(), getExportDlgMsgi18nKey(),
                list, CustomDialog.OKCANCELHELP, ToggleButtonChooserPanel.Type.Checkbox);
        dlg.setAddSelectAll(true);
        dlg.setUseScrollPane(true);
        dlg.setHelpContext(getExportHelpContext());
        UIHelper.centerAndShow(dlg);
        selectedList = dlg.getSelectedObjects();
        if (dlg.isCancelled() || selectedList.size() == 0) {
            return;
        }
    }

    String path = AppPreferences.getLocalPrefs().get(XML_PATH_PREF, null);

    FileDialog fDlg = new FileDialog(((Frame) UIRegistry.getTopWindow()), UIRegistry.getResourceString("SAVE"),
            FileDialog.SAVE);
    if (path != null) {
        fDlg.setDirectory(path);
    }
    fDlg.setVisible(true);

    String dirStr = fDlg.getDirectory();
    String fileName = fDlg.getFile();
    if (StringUtils.isEmpty(dirStr) || StringUtils.isEmpty(fileName)) {
        return;
    }

    if (StringUtils.isEmpty(FilenameUtils.getExtension(fileName))) {
        fileName += ".xml";
    }
    path = dirStr + fileName;
    AppPreferences.getLocalPrefs().put(XML_PATH_PREF, path);

    Hashtable<String, Boolean> hash = new Hashtable<String, Boolean>();
    for (String qTitle : selectedList) {
        hash.put(qTitle, true);
    }

    Vector<SpQuery> queries = new Vector<SpQuery>();

    // Persist out to database
    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();
        for (NavBoxItemIFace nbi : navBox.getItems()) {
            if (hash.get(nbi.getTitle()) != null) {
                RecordSetIFace rs = (RecordSetIFace) nbi.getData();
                if (rs != null) {
                    SpQuery query = session.get(SpQuery.class, rs.getOnlyItem().getRecordId());
                    queries.add(query);
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(getXMLExportFirstLine());
        for (SpQuery q : queries) {
            q.toXML(sb);
        }
        sb.append(getXMLExportLastLine());
        FileUtils.writeStringToFile(new File(path), sb.toString());

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryTask.class, ex);
        // XXX Error dialog
        ex.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:base.BasePlayer.Main.java

void openProject() {

    /*JFileChooser chooser = new JFileChooser(Main.projectDir);   
            /*w  w  w .j  a  v  a  2 s. c  o m*/
    chooser.setAcceptAllFileFilterUsed(false);
      MyFilterSES sesFilter = new MyFilterSES();            
      chooser.addChoosableFileFilter(sesFilter);
      chooser.setDialogTitle("Open project");
      chooser.setPreferredSize(new Dimension((int)screenSize.getWidth()/3, (int)screenSize.getHeight()/3));
     int returnVal = chooser.showOpenDialog((Component)this.getParent());                        
     */
    FileRead.asked = false;

    FileDialog fc = new FileDialog(frame, "Choose project file", FileDialog.LOAD);
    fc.setDirectory(Main.projectDir);
    fc.setFile("*.ses");
    fc.setFilenameFilter(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".ses");
        }
    });
    fc.setMultipleMode(false);
    fc.setVisible(true);
    String openfile = fc.getFile();

    if (openfile != null) {
        File addfile = new File(fc.getDirectory() + "/" + openfile);
        projectDir = fc.getDirectory();
        writeToConfig("DefaultProjectDir=" + projectDir);
        clearData();
        OpenProject opener = new OpenProject(addfile);
        opener.execute();
    }
    /* if (returnVal == JFileChooser.APPROVE_OPTION) {
                   
           projectDir = chooser.getSelectedFile().getParent();       
         writeToConfig("DefaultProjectDir=" +projectDir);
         OpenProject opener = new OpenProject(chooser.getSelectedFile());
         opener.execute();
     }*/
}

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);
        }//  w  ww  .  ja  va 2s.  c o  m
        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:no.java.swing.SingleSelectionFileDialog.java

private Result showNativeDialog(Component target, boolean open) {
    Window window = target == null ? null : (Frame) SwingUtilities.getWindowAncestor(target);
    FileDialog dialog;
    if (window instanceof Frame) {
        dialog = new FileDialog((Frame) window);
    } else if (window instanceof Dialog) {
        dialog = new FileDialog((Dialog) window);
    } else {/*from www.  j  a  v a 2  s.  c o m*/
        throw new IllegalStateException("Unknown window type");
    }
    dialog.setDirectory(previousDirectory.getAbsolutePath());
    dialog.setMode(open ? FileDialog.LOAD : FileDialog.SAVE);
    dialog.setVisible(true);
    if (rememberPreviousLocation) {
        previousDirectory = new File(dialog.getDirectory());
    }
    if (dialog.getFile() == null) {
        return Result.CANCEL;
    }
    selected = new File(dialog.getFile());
    return Result.APPROVE;
}

From source file:org.cds06.speleograph.actions.OpenAction.java

/**
 * Invoked when an action occurs./*from  ww w  . j ava 2  s.  c om*/
 */
@Override
public void actionPerformed(ActionEvent e) {
    chooser.setCurrentDirectory(SpeleoGraphApp.getWorkingDirectory());
    File file = null;
    if (SpeleoGraphApp.isMac()) {
        do {
            if (file != null && !fileFilter.accept(file)) {
                JOptionPane.showMessageDialog(SpeleoGraphApp.getInstance(),
                        I18nSupport.translate("actions.open.formaterror"), I18nSupport.translate("error"),
                        JOptionPane.ERROR_MESSAGE);
            }
            FileDialog chooserMac = new FileDialog(SpeleoGraphApp.getInstance());
            chooserMac.setDirectory(SpeleoGraphApp.getWorkingDirectory().getAbsolutePath());
            chooserMac.setVisible(true);
            if (chooserMac.getFile() == null)
                return;
            file = FileUtils.getFile(chooserMac.getDirectory(), chooserMac.getFile());
            if (file.isDirectory())
                return;
        } while (!fileFilter.accept(file));
    } else {
        int result = chooser.showOpenDialog(parent);
        switch (result) {
        case JFileChooser.APPROVE_OPTION:
            file = chooser.getSelectedFile();
            if (file.isDirectory())
                return;
            break;
        case JFileChooser.CANCEL_OPTION:
        default:
            SpeleoGraphApp.setWorkingDirectory(chooser.getCurrentDirectory());
            return;
        }
    }
    try {
        SpeleoGraphApp.setWorkingDirectory(file.getParentFile());
        reader.readFile(file);
    } catch (FileReadingError e1) {
        log.error("Error when try to read a SpeleoGraph File", e1);
    }
}

From source file:org.neo4j.desktop.ui.BrowseForDatabaseActionListener.java

private File macFileSelection() {
    System.setProperty("apple.awt.fileDialogForDirectories", "true");
    FileDialog fileDialog = new FileDialog(frame);

    fileDialog.setDirectory(directoryDisplay.getText());
    fileDialog.setVisible(true);/*from ww  w.  j  av  a2s . c  o  m*/

    File selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
    System.setProperty("apple.awt.fileDialogForDirectories", "false");

    return selectedFile;
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

private static Path openDirectoryDialog(String title) throws Exception, Error {
    // set system property to choose directories
    System.setProperty("apple.awt.fileDialogForDirectories", "true");

    FileDialog chooser = new FileDialog(MainWindow.getFrame(), title);
    if (lastDir != null) {
        chooser.setDirectory(lastDir.toFile().getAbsolutePath());
    }/*from   w ww. j  a  va 2s . c om*/
    chooser.setVisible(true);

    // reset system property
    System.setProperty("apple.awt.fileDialogForDirectories", "false");

    if (StringUtils.isNotEmpty(chooser.getFile())) {
        lastDir = Paths.get(chooser.getDirectory());
        return Paths.get(chooser.getDirectory(), chooser.getFile());
    } else {
        return null;
    }
}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

private static Path openFileDialog(String title, int mode, String filename) throws Exception, Error {
    FileDialog chooser = new FileDialog(MainWindow.getFrame(), title, mode);
    if (lastDir != null) {
        chooser.setDirectory(lastDir.toFile().getAbsolutePath());
    }/*from   ww  w. ja  v a  2  s. c o m*/
    if (mode == FileDialog.SAVE) {
        chooser.setFile(filename);
    }
    chooser.setVisible(true);

    if (StringUtils.isNotEmpty(chooser.getFile())) {
        lastDir = Paths.get(chooser.getDirectory());
        return Paths.get(chooser.getDirectory(), chooser.getFile());
    } else {
        return null;
    }
}

From source file:processing.app.Base.java

/**
 * Prompt for a sketch to open, and open it in a new window.
 *
 * @throws Exception//from   w w  w .j av  a2s.  c o m
 */
public void handleOpenPrompt() throws Exception {
    // get the frontmost window frame for placing file dialog
    FileDialog fd = new FileDialog(activeEditor, tr("Open an Arduino sketch..."), FileDialog.LOAD);
    File lastFolder = new File(
            PreferencesData.get("last.folder", BaseNoGui.getSketchbookFolder().getAbsolutePath()));
    if (lastFolder.exists() && lastFolder.isFile()) {
        lastFolder = lastFolder.getParentFile();
    }
    fd.setDirectory(lastFolder.getAbsolutePath());

    // Only show .pde files as eligible bachelors
    fd.setFilenameFilter(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".ino") || name.toLowerCase().endsWith(".pde");
        }
    });

    fd.setVisible(true);

    String directory = fd.getDirectory();
    String filename = fd.getFile();

    // User canceled selection
    if (filename == null)
        return;

    File inputFile = new File(directory, filename);

    PreferencesData.set("last.folder", inputFile.getAbsolutePath());
    handleOpen(inputFile);
}

From source file:processing.app.Sketch.java

/**
 * Handles 'Save As' for a sketch.//from   w  w  w  .  j  a v a2s  .  c o  m
 * <P>
 * This basically just duplicates the current sketch folder to
 * a new location, and then calls 'Save'. (needs to take the current
 * state of the open files and save them to the new folder..
 * but not save over the old versions for the old sketch..)
 * <P>
 * Also removes the previously-generated .class and .jar files,
 * because they can cause trouble.
 */
protected boolean saveAs() throws IOException {
    // get new name for folder
    FileDialog fd = new FileDialog(editor, tr("Save sketch folder as..."), FileDialog.SAVE);
    if (isReadOnly(BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath())
            || isUntitled()) {
        // default to the sketchbook folder
        fd.setDirectory(BaseNoGui.getSketchbookFolder().getAbsolutePath());
    } else {
        // default to the parent folder of where this was
        // on macs a .getParentFile() method is required

        fd.setDirectory(data.getFolder().getParentFile().getAbsolutePath());
    }
    String oldName = data.getName();
    fd.setFile(oldName);

    fd.setVisible(true);
    String newParentDir = fd.getDirectory();
    String newName = fd.getFile();

    // user canceled selection
    if (newName == null)
        return false;
    newName = Sketch.checkName(newName);

    File newFolder = new File(newParentDir, newName);

    // make sure there doesn't exist a .cpp file with that name already
    // but ignore this situation for the first tab, since it's probably being
    // resaved (with the same name) to another location/folder.
    for (int i = 1; i < data.getCodeCount(); i++) {
        SketchCode code = data.getCode(i);
        if (newName.equalsIgnoreCase(code.getPrettyName())) {
            Base.showMessage(tr("Error"), I18n.format(tr("You can't save the sketch as \"{0}\"\n"
                    + "because the sketch already has a file with that name."), newName));
            return false;
        }
    }

    // check if the paths are identical
    if (newFolder.equals(data.getFolder())) {
        // just use "save" here instead, because the user will have received a
        // message (from the operating system) about "do you want to replace?"
        return save();
    }

    // check to see if the user is trying to save this sketch inside itself
    try {
        String newPath = newFolder.getCanonicalPath() + File.separator;
        String oldPath = data.getFolder().getCanonicalPath() + File.separator;

        if (newPath.indexOf(oldPath) == 0) {
            Base.showWarning(tr("How very Borges of you"), tr(
                    "You cannot save the sketch into a folder\n" + "inside itself. This would go on forever."),
                    null);
            return false;
        }
    } catch (IOException e) {
        //ignore
    }

    // if the new folder already exists, then need to remove
    // its contents before copying everything over
    // (user will have already been warned)
    if (newFolder.exists()) {
        Base.removeDir(newFolder);
    }
    // in fact, you can't do this on windows because the file dialog
    // will instead put you inside the folder, but it happens on osx a lot.

    // now make a fresh copy of the folder
    newFolder.mkdirs();

    // grab the contents of the current tab before saving
    // first get the contents of the editor text area
    if (current.getCode().isModified()) {
        current.getCode().setProgram(editor.getText());
    }

    // save the other tabs to their new location
    for (SketchCode code : data.getCodes()) {
        if (data.indexOfCode(code) == 0)
            continue;
        File newFile = new File(newFolder, code.getFileName());
        code.saveAs(newFile);
    }

    // re-copy the data folder (this may take a while.. add progress bar?)
    if (data.getDataFolder().exists()) {
        File newDataFolder = new File(newFolder, "data");
        Base.copyDir(data.getDataFolder(), newDataFolder);
    }

    // re-copy the code folder
    if (data.getCodeFolder().exists()) {
        File newCodeFolder = new File(newFolder, "code");
        Base.copyDir(data.getCodeFolder(), newCodeFolder);
    }

    // copy custom applet.html file if one exists
    // http://dev.processing.org/bugs/show_bug.cgi?id=485
    File customHtml = new File(data.getFolder(), "applet.html");
    if (customHtml.exists()) {
        File newHtml = new File(newFolder, "applet.html");
        Base.copyFile(customHtml, newHtml);
    }

    // save the main tab with its new name
    File newFile = new File(newFolder, newName + ".ino");
    data.getCode(0).saveAs(newFile);

    editor.handleOpenUnchecked(newFile, currentIndex, editor.getSelectionStart(), editor.getSelectionStop(),
            editor.getScrollPosition());

    // Name changed, rebuild the sketch menus
    //editor.sketchbook.rebuildMenusAsync();
    editor.base.rebuildSketchbookMenus();

    // Make sure that it's not an untitled sketch
    setUntitled(false);

    // let Editor know that the save was successful
    return true;
}