Example usage for javax.swing JFileChooser setCurrentDirectory

List of usage examples for javax.swing JFileChooser setCurrentDirectory

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "The directory that the JFileChooser is showing files of.")
public void setCurrentDirectory(File dir) 

Source Link

Document

Sets the current directory.

Usage

From source file:Main.java

public static String browseForFile(Window owner, String file, int selectionMode, String title,
        FileFilter filter) {//from www. j  ava2 s .c  om
    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: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.  jav 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:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory.//w w  w  .  ja v  a 2 s.  com
 *
 *
 * @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:Main.java

/**
 * Displays a {@link JFileChooser} to select a file.
 *
 * @param title The title of the dialog.
 * @param startDirectory The directory where the dialog is initialed opened.
 * @param fileExtension File extension to filter each content of the opened
 * directories. Example ".xml".// ww w  .j a  v a2 s. co  m
 * @param startFile The preselected file where the dialog is initialed opened.
 * @return The {@link File} object selected, returns null if no file was selected.
 */
public static File chooseFile(String title, String startDirectory, final String fileExtension,
        String startFile) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle(title);

    if (fileExtension != null && !fileExtension.trim().equals("")) {
        FileFilter filter = new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() || pathname.getName().endsWith(fileExtension);
            }

            @Override
            public String getDescription() {
                return "(" + fileExtension + ")";
            }
        };

        chooser.setFileFilter(filter);
    }

    if (startDirectory != null && !startDirectory.trim().equals("")) {
        chooser.setCurrentDirectory(new File(startDirectory));
    }

    if (startFile != null && !startFile.trim().equals("")) {
        chooser.setSelectedFile(new File(startFile));
    }

    int status = chooser.showOpenDialog(null);

    if (status == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    }

    return null;
}

From source file:com.opendoorlogistics.core.utils.ui.FileBrowserPanel.java

private static JButton createBrowseButton(final boolean directoriesOnly, final String browserApproveButtonText,
        final JTextField textField, final FileFilter... fileFilters) {
    JButton browseButton = new JButton("...");
    browseButton.addActionListener(new ActionListener() {

        @Override/*from   ww w . j  av  a  2s .c o m*/
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();

            if (textField.getText() != null) {
                File file = new File(textField.getText());

                // if the file doesn't exist but the directory does, get that
                if (!file.exists() && file.getParentFile() != null && file.getParentFile().exists()) {
                    file = file.getParentFile();
                }

                if (!directoriesOnly && file.isFile()) {
                    chooser.setSelectedFile(file);
                }

                if (file.isDirectory() && file.exists()) {
                    chooser.setCurrentDirectory(file);
                }
            }

            if (directoriesOnly) {
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            }

            // add filters and automatically select correct one
            if (fileFilters.length == 1) {
                chooser.setFileFilter(fileFilters[0]);
            } else {
                for (FileFilter filter : fileFilters) {
                    chooser.addChoosableFileFilter(filter);
                    if (filter instanceof FileNameExtensionFilter) {
                        if (matchesFilter((FileNameExtensionFilter) filter, textField.getText())) {
                            chooser.setFileFilter(filter);
                        }
                    }
                }
            }

            if (chooser.showDialog(textField, browserApproveButtonText) == JFileChooser.APPROVE_OPTION) {
                //File selected = processSelectedFile(chooser.getSelectedFile());
                File selected = chooser.getSelectedFile();

                String path = selected.getPath();
                FileFilter filter = chooser.getFileFilter();
                if (filter != null && filter instanceof FileNameExtensionFilter) {

                    boolean found = matchesFilter(((FileNameExtensionFilter) chooser.getFileFilter()), path);

                    if (!found) {
                        String[] exts = ((FileNameExtensionFilter) chooser.getFileFilter()).getExtensions();
                        if (exts.length > 0) {
                            path = FilenameUtils.removeExtension(path);
                            path += "." + exts[0];
                        }
                    }

                }
                textField.setText(path);
            }
        }
    });

    return browseButton;
}

From source file:Main.java

public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();
    if (source == openItem) {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.setFileFilter(new FileFilter() {
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".zip") || f.isDirectory();
            }/*from  ww  w.ja v a2s. c  om*/

            public String getDescription() {
                return "ZIP Files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String zipname = chooser.getSelectedFile().getPath();
            System.out.println(zipname);
        }
    } else if (source == exitItem)
        System.exit(0);
}

From source file:ImageViewer.java

public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();
    if (source == openItem) {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));

        chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
            }/*from   ww w  .jav  a2 s  . co  m*/

            public String getDescription() {
                return "GIF Images";
            }
        });

        int r = chooser.showOpenDialog(this);
        if (r == JFileChooser.APPROVE_OPTION) {
            String name = chooser.getSelectedFile().getName();
            label.setIcon(new ImageIcon(name));
        }
    } else if (source == exitItem)
        System.exit(0);
}

From source file:MessageDigestTest.java

public void loadFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    int r = chooser.showOpenDialog(this);
    if (r == JFileChooser.APPROVE_OPTION) {
        String name = chooser.getSelectedFile().getAbsolutePath();
        computeDigest(loadBytes(name));//from w w  w.j  ava2 s.c  om
    }
}

From source file:MessageDigestTest.java

/**
 * Loads a file and computes its message digest.
 *//*from w  w  w .j a  v  a  2s  .c o m*/
public void loadFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    int r = chooser.showOpenDialog(this);
    if (r == JFileChooser.APPROVE_OPTION) {
        try {
            String name = chooser.getSelectedFile().getAbsolutePath();
            computeDigest(loadBytes(name));
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
}

From source file:de.burrotinto.jKabel.dbauswahlAS.DBAuswahlAAS.java

private String choosePath(String pfad) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File(pfad));
    chooser.setDialogTitle("DB Pfad");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);
    return chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION ? null
            : chooser.getSelectedFile().getPath() + File.separator;

}