Example usage for javax.swing JFileChooser getSelectedFile

List of usage examples for javax.swing JFileChooser getSelectedFile

Introduction

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

Prototype

public File getSelectedFile() 

Source Link

Document

Returns the selected file.

Usage

From source file:marytts.tools.voiceimport.DatabaseImportMain.java

private static File determineVoiceBuildingDir(String[] args) {
    // Determine the voice building directory in the following order:
    // 1. System property "user.dir"
    // 2. First command line argument
    // 3. current directory
    // 4. Prompt user via gui.
    // Do a sanity check -- do they exist, do they have a wav/ subdirectory?

    String voiceBuildingDir = null;
    Vector<String> candidates = new Vector<String>();
    candidates.add(System.getProperty("user.dir"));
    if (args.length > 0)
        candidates.add(args[0]);//from   ww w. j ava  2 s . c  o  m
    candidates.add("."); // current directory
    for (String dir : candidates) {
        if (dir != null && new File(dir).isDirectory() && new File(dir + "/wav").isDirectory()) {
            voiceBuildingDir = dir;
            break;
        }
    }
    if (voiceBuildingDir == null) { // need to ask user
        JFrame window = new JFrame("This is the Frames's Title Bar!");
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Choose Voice Building Directory");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        System.out.println("Opening GUI....... ");
        //outDir.setText(file.getAbsolutePath());
        //System.exit(0);
        int returnVal = fc.showOpenDialog(window);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (file != null)
                voiceBuildingDir = file.getAbsolutePath();
        }
    }
    System.setProperty("user.dir", voiceBuildingDir);
    if (voiceBuildingDir != null) {
        return new File(voiceBuildingDir);
    } else {
        return null;
    }
}

From source file:ca.licef.lompad.Classification.java

public static File doImportFile(Component parent) {
    JFileChooser chooser = new JFileChooser();
    if (Preferences.getInstance().getPrevClassifDir() != null)
        chooser.setCurrentDirectory(Preferences.getInstance().getPrevClassifDir());
    int returnVal = chooser.showOpenDialog(parent);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {//from   w w w .ja v  a2s  . c om
            Preferences.getInstance().setPrevClassifDir(chooser.getCurrentDirectory());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            File skosInputFile = chooser.getSelectedFile();
            File tmpFile = null;

            String xml = IOUtil.readStringFromFile(chooser.getSelectedFile());
            String rootTagName = XMLUtil.getRootTagName(xml);
            if (rootTagName != null) {
                String[] array = StringUtil.split(rootTagName, ':');
                rootTagName = array[array.length - 1].toLowerCase();
            }
            boolean isVdexFile = (rootTagName != null && "vdex".equals(rootTagName));
            if (isVdexFile) {
                String xsltFile = "/xslt/convertVDEXToSKOS.xsl";
                StreamSource xslt = new StreamSource(Util.class.getResourceAsStream(xsltFile));

                StreamSource xmlSource = new StreamSource(new BufferedReader(new StringReader(xml)));

                Node skosNode = XMLUtil.applyXslToDocument2(xslt, xmlSource, null, null, null);
                tmpFile = File.createTempFile("lompad", "inputSkos");
                Writer tmpFileWriter = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(tmpFile, false), "UTF-8"));

                try {
                    XMLUtil.serialize(skosNode, false, tmpFileWriter);
                } finally {
                    if (tmpFileWriter != null)
                        tmpFileWriter.close();
                }
                skosInputFile = tmpFile;
            }

            Classification classif = new Classification(skosInputFile);
            classif.initModel(true);
            String uri = classif.getConceptSchemeUri();
            if (uri == null)
                throw new Exception("ConceptScheme's URI not found.");
            String sha1 = DigestUtils.shaHex(uri);
            File localFile = new File(Util.getClassificationFolder(), sha1 + ".rdf");
            classif.dumpModelToRdf(localFile);

            if (tmpFile != null)
                tmpFile.delete();

            return (localFile);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "classifImportFailed";
            if ("Classification identifier not found.".equals(e.getMessage()))
                msg = "classifIdentifierNotFound";
            JDialogAlert dialog = new JDialogAlert(Util.getTopJFrame((Container) parent), "titleErr", msg);
            dialog.setSize(320, 140);
            dialog.setVisible(true);
            return (null);
        }
    } else
        return (null);
}

From source file:com.igormaznitsa.ideamindmap.utils.IdeaUtils.java

public static File chooseFile(final Component parent, final boolean filesOnly, final String title,
        final File selectedFile, final FileFilter filter) {
    final JFileChooser chooser = new JFileChooser(selectedFile);

    chooser.setApproveButtonText("Select");
    if (filter != null)
        chooser.setFileFilter(filter);/* ww  w.  j a v  a 2 s .  c  o m*/

    chooser.setDialogTitle(title);
    chooser.setMultiSelectionEnabled(false);

    if (filesOnly)
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    else
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    } else {
        return null;
    }
}

From source file:Main.java

public static String browseForFile(Window owner, String file, int selectionMode, String title,
        FileFilter filter) {/*  w  w  w  . j av a 2  s .com*/
    final String curDir = System.getProperty("user.dir");
    JFileChooser chooser = new JFileChooser(curDir);
    chooser.setDialogType(JFileChooser.OPEN_DIALOG);
    chooser.setFileSelectionMode(selectionMode);
    chooser.setApproveButtonText("Select");
    chooser.setApproveButtonMnemonic('s');
    chooser.setDialogTitle(title);
    if (filter != null)
        chooser.setFileFilter(filter);

    if (file != null && !file.isEmpty()) {
        File curFile = new File(file);

        chooser.setCurrentDirectory(curFile.getAbsoluteFile().getParentFile());

        if (curFile.isDirectory()) {
            try {
                chooser.setSelectedFile(curFile.getCanonicalFile());
            } catch (IOException ex) {
            }
        } else {
            chooser.setSelectedFile(curFile);
        }
    }

    if (chooser.showOpenDialog(owner) == JFileChooser.APPROVE_OPTION) {
        String path = chooser.getSelectedFile().getPath();
        try {
            path = new File(path).getCanonicalPath();
        } catch (IOException e) {
        }
        // make path relative if possible
        if (path.startsWith(curDir)) {
            path = "." + path.substring(curDir.length());
        }

        return path;
    }
    return null;
}

From source file:com.rpgsheet.xcom.PimpMyXcom.java

private static void openXcomPathDialog(Properties appProperties) {
    // display the box to the user
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("PimpMyXcom - Where is X-COM?");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int retCode = fileChooser.showOpenDialog(null);
    // if the user cancelled the dialog, there is nothing we can do
    if (retCode == JFileChooser.CANCEL_OPTION) {
        log.error("User cancel while attempting to locate X-COM.");
        return;/*from  w w w . ja  va2  s . com*/
    }
    // if there was an error, there is nothing we can do
    if (retCode == JFileChooser.ERROR_OPTION) {
        log.error("Error while attempting to locate X-COM: {}", JFileChooser.ERROR_OPTION);
        return;
    }
    // if the user chose a directory, then we have some work to do
    String xcomPath = fileChooser.getSelectedFile().getAbsolutePath();
    File xcomDir = new File(xcomPath);
    if (containsXcom(xcomDir)) {
        // store the path to xcom in the application properties
        appProperties.setProperty("xcom.path", xcomPath);
        // write the updated application properties to disk
        try {
            saveApplicationProperties(appProperties);
        } catch (IOException e) {
            log.error("Unable to store X-COM path in application properties.", e);
            return;
        }
    }
    // if we were unable to find X-COM
    else {
        log.error("User provided location did not contain X-COM.");
        return;
    }
}

From source file:com.sciaps.utils.Util.java

public static void saveCSVFile(StringBuilder strBuilder) {
    JFileChooser chooser = new JFileChooser();

    int retrival = chooser.showSaveDialog(Constants.MAIN_FRAME);
    if (retrival == JFileChooser.APPROVE_OPTION) {

        ProgressStatusPanel progressbar = new ProgressStatusPanel();
        final CustomDialog progressDialog = new CustomDialog(Constants.MAIN_FRAME, "Exporting CSV file",
                progressbar, CustomDialog.NONE_OPTION);
        progressDialog.setSize(400, 100);
        SwingUtilities.invokeLater(new Runnable() {

            @Override//from  www. j  a v a  2  s. co m
            public void run() {
                progressDialog.setVisible(true);
            }
        });

        try {
            String fileName = chooser.getSelectedFile().toString();
            if (!fileName.endsWith(".csv") && !fileName.endsWith(".CSV")) {
                fileName = fileName + ".csv";
            }
            FileWriter fw = new FileWriter(fileName);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(strBuilder.toString());
            bw.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }

        progressDialog.dispose();
    }
}

From source file:at.tuwien.ifs.somtoolbox.apps.viewer.fileutils.ExportUtils.java

public static File getFilePath(Component parent, JFileChooser fileChooser, String title, String defaultFileName,
        FileFilter filter) {/*from  w  w w.java  2 s  .  c  o m*/
    fileChooser = initFileChooser(fileChooser, filter);
    if (org.apache.commons.lang.StringUtils.isNotBlank(defaultFileName)) {
        fileChooser.setSelectedFile(new File(defaultFileName));
    }
    int returnVal = fileChooser.showDialog(parent, title);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return fileChooser.getSelectedFile();
    } else {
        return null;
    }
}

From source file:ch.admin.hermes.etl.load.HermesETLApplication.java

/**
 * FileOpen Dialog// w  w w . j av  a  2 s.  c o m
 * @param title
 * @param name
 * @param ext
 * @return
 */
private static String getFile(final String title, final String[] name, final String[] ext) {
    // User Chooses a Path and Name for the html Output File
    JFileChooser fc = new JFileChooser(".");
    fc.setDialogType(JFileChooser.OPEN_DIALOG);
    fc.setDialogTitle(title);
    fc.setFileFilter(new FileFilter() {
        public String getDescription() {
            StringBuffer str = new StringBuffer();
            for (String n : name)
                str.append(n + "");
            return (str.toString());
        }

        public boolean accept(File f) {
            for (String e : ext)
                if (f.isDirectory() || f.getName().toLowerCase().endsWith(e))
                    return (true);
            return false;
        }
    });

    int state = fc.showOpenDialog(null);

    if (state == JFileChooser.APPROVE_OPTION)
        return (fc.getSelectedFile().getPath());

    return (null);
}

From source file:com.imag.nespros.gui.plugin.GraphEditor.java

private static void initMenu() {
    JMenu menu = new JMenu("File");
    menu.add(new AbstractAction("Make Image") {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(demo);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                demo.writeJPEGImage(file);
            }/*from  w ww . java  2s . com*/
        }
    });
    menu.add(new AbstractAction("Print") {
        public void actionPerformed(ActionEvent e) {
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setPrintable(demo);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    });
    menu.add(new AbstractAction("Save topology") {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(demo);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    demo.save(file);
                    frame.setTitle(file.getName());
                } catch (IOException ex) {
                    Logger.getLogger(GraphEditor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });
    menu.add(new AbstractAction("Load topology") {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showOpenDialog(demo);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    //EPGraph.getInstance().resetMapping();
                    simu.resetMapping();
                    demo.load(file);
                    frame.setTitle("Simulator - " + file.getName());
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(GraphEditor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });
    JMenu menu2 = new JMenu("View");
    menu2.add(new AbstractAction("Layout") {
        @Override
        public void actionPerformed(ActionEvent e) {
            Layout l = new CircleLayout<Device, ComLink>(Topology.getInstance().getGraph());
            l.setInitializer(vv.getGraphLayout());
            l.setSize(vv.getSize());
            LayoutTransition<Device, ComLink> lt = new LayoutTransition<>(vv, vv.getGraphLayout(), l);
            Animator animator = new Animator(lt);
            animator.start();
            vv.getRenderContext().getMultiLayerTransformer().setToIdentity();
            vv.repaint();
        }
    });
    menu2.add(new AbstractAction("Event Composition Networks") {
        @Override
        public void actionPerformed(ActionEvent e) {
            showEPGraph(EPGraph.getInstance().getGraph());
        }
    });
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    menuBar.add(menu2);
    frame.setJMenuBar(menuBar);
    frame.getContentPane().add(demo);
    frame.pack();
    frame.setVisible(true);
    buildEPGraphs();
    showEPGraph(EPGraph.getInstance().getGraph());
}

From source file:CoreJavaSound.java

public CoreJavaSound() throws Exception {
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);/*ww  w  . j  av a  2 s.  c o  m*/
    soundFile = chooser.getSelectedFile();

    System.out.println("Playing " + soundFile.getName());

    Line.Info linfo = new Line.Info(Clip.class);
    Line line = AudioSystem.getLine(linfo);
    clip = (Clip) line;
    clip.addLineListener(this);
    AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
    clip.open(ais);
    clip.start();
}