Example usage for javax.swing JFileChooser showOpenDialog

List of usage examples for javax.swing JFileChooser showOpenDialog

Introduction

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

Prototype

public int showOpenDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up an "Open File" file chooser dialog.

Usage

From source file:Main.java

public static String showOpenFile(String currentDirectoryPath, Component parent, final String filterRegex,
        final String filterDescription) {
    JFileChooser fileChooser = new JFileChooser(currentDirectoryPath);
    fileChooser.addChoosableFileFilter(new FileFilter() {
        private Pattern regexPattern = Pattern.compile(filterRegex);

        public boolean accept(File f) {
            if (f.isDirectory())
                return true;
            return regexPattern.matcher(f.getName()).matches();
        }/*from w w w  .java 2s  . c o  m*/

        public String getDescription() {
            return filterDescription;
        }

    });
    fileChooser.showOpenDialog(parent);

    File choosedFile = fileChooser.getSelectedFile();
    if (choosedFile == null)
        return null;
    return choosedFile.getAbsolutePath();
}

From source file:Main.java

/**
 * Consistent way to chosing multiple files to open with JFileChooser.
 * <p>//from  w w  w. j a  va 2s.c  o  m
 * 
 * @see JFileChooser#setFileSelectionMode(int)
 * @see #getSystemFiles(Component, int)
 * @param owner to show the component relative to.
 * @param mode selection mode for the JFileChooser.
 * @return File[] based on the user selection can be null.
 */
public static File[] getSystemFiles(Component owner, int mode, FileFilter[] filters) {

    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(mode);
    jfc.setFileHidingEnabled(true);
    jfc.setMultiSelectionEnabled(true);
    jfc.setAcceptAllFileFilterUsed(true);
    if (filters != null) {
        for (int i = 0; i < filters.length; i++) {
            jfc.addChoosableFileFilter(filters[i]);
        }

        if (filters.length >= 1) {
            jfc.setFileFilter(filters[0]);
        }
    }

    int result = jfc.showOpenDialog(owner);
    if (result == JFileChooser.APPROVE_OPTION) {
        return jfc.getSelectedFiles();
    }

    return new File[0];
}

From source file:Main.java

/**
 * Opens a file chooser dialog// ww w . ja va  2 s. c  o  m
 * @param chooseAFolder true if the dialog should return a folder, false for a file
 */
public static String chooseFile(JComboBox comboBox, boolean chooseAFolder) {
    JFileChooser chooser = new JFileChooser();
    String path = "";
    String currentDir = "";

    if (comboBox.getSelectedItem() != null) {
        currentDir = comboBox.getSelectedItem().toString();
    }

    // Set whether we want to select a folder instead of a file
    if (chooseAFolder) {
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    }

    chooser.setCurrentDirectory(new File(currentDir));

    // Show open dialog; this method does not return until the dialog is closed
    if (chooser.showOpenDialog(comboBox) == JFileChooser.APPROVE_OPTION) {
        path = chooser.getSelectedFile().getAbsolutePath();
    }

    if (path == null || path.equals("")) {
        return currentDir;
    }
    return path;
}

From source file:Main.java

/**
 * Dialog for choosing file.// ww w .jav  a 2  s . c  o  m
 * 
 * @param parent the parent component of the dialog, can be null
 * @return selected file or null if no file is selected
 */
public static File chooseImageFile(Component parent) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileFilter() {
        @Override
        public String getDescription() {
            return "Supported image files(JPEG, PNG, BMP)";
        }

        @Override
        public boolean accept(File f) {
            String name = f.getName();
            boolean accepted = f.isDirectory() || name.endsWith(".jpg") || name.endsWith(".jpeg")
                    || name.endsWith(".png") || name.endsWith(".bmp");
            return accepted;
        }
    });

    fileChooser.showOpenDialog(parent);
    return fileChooser.getSelectedFile();
}

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 {/*w  w  w  . j ava  2s  . 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:Main.java

/**
 * Dialog for choosing file.//  w ww.j av  a 2  s . co m
 * 
 * @param parent the parent component of the dialog, can be null
 * @return selected file or null if no file is selected
 */
public static File chooseImageFile(Component parent) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileFilter() {
        @Override
        public String getDescription() {
            return "Supported image files(JPEG, PNG, BMP)";
        }

        @Override
        public boolean accept(File f) {
            String name = f.getName();
            boolean accepted = f.isDirectory() || name.endsWith(".jpg") || name.endsWith(".jpeg")
                    || name.endsWith(".jp2") || name.endsWith(".png") || name.endsWith(".bmp");
            return accepted;
        }
    });

    fileChooser.showOpenDialog(parent);
    return fileChooser.getSelectedFile();
}

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  va2s.c om*/
        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:SwingUtil.java

/**
 * Get a file selection using the FileChooser dialog.
 *
 * @param owner/* w  w w  .  j  av a 2s .co m*/
 * The parent of this modal dialog.
 * @param defaultSelection
 * The default file selection as a file.
 * @param filter
 * An extension filter
 * @param title
 * The caption for the dialog.
 *
 * @return
 * A selected file or null if no selection is made.
 */
public static File getFileChoice(Component owner, File defaultSelection, FileFilter filter, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    File choice = null;
    JFileChooser chooser = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);

    chooser = new JFileChooser();
    if (defaultSelection.isDirectory()) {
        chooser.setCurrentDirectory(defaultSelection);
    } else {
        chooser.setSelectedFile(defaultSelection);
    }
    chooser.setFileFilter(filter);
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            choice = chooser.getSelectedFile();
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory.//w  w w  .  j a  v  a2  s  . c o  m
 *
 *
 * @param owner
 * The frame or dialog that controls the invokation of this dialog.
 * @param defaultDir
 * The directory to show when the dialog opens.
 * @param title
 * Tile for the dialog.
 *
 * @return
 * The selected directory as a File. Null if user cancels dialog without
 * a selection.
 *
 */
public static File getDirectoryChoice(Component owner, File defaultDir, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    JFileChooser chooser = null;
    File choice = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);
    chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    if ((defaultDir != null) && defaultDir.exists() && defaultDir.isDirectory()) {
        chooser.setCurrentDirectory(defaultDir);
        chooser.setSelectedFile(defaultDir);
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            if (chooser.getSelectedFile().exists()) {
                choice = chooser.getSelectedFile();
            } else {
                File parentFile = new File(chooser.getSelectedFile().getParent());

                choice = parentFile;
            }
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

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.ja  va2s  .  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;
    }
}