Java JFileChooser getDir(String title, String initDir, boolean allowFiles, Component parent)

Here you can find the source of getDir(String title, String initDir, boolean allowFiles, Component parent)

Description

Prompt the user to select a directory (or file).

License

Open Source License

Parameter

Parameter Description
title the dialog title
initDir the initial directory
allowFiles should we allow non-directory files
parent the parent component to use for the JFileChooser

Return

the selected file or null if there is no valid selection

Declaration

public static File getDir(String title, String initDir, boolean allowFiles, Component parent) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Component;

import java.io.File;

import javax.swing.JFileChooser;

public class Main {
    /**/*from w w w  .ja v a2 s.  c om*/
     * Prompt the user to select a directory (or file). This function should
     * only be called from the AWT thread
     * @param title the dialog title
     * @param initDir the initial directory
     * @param allowFiles should we allow non-directory files
     * @param parent the parent component to use for the JFileChooser
     * @return the selected file or null if there is no valid selection
     */
    public static File getDir(String title, String initDir, boolean allowFiles, Component parent) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle(title);
        fileChooser.setFileSelectionMode(
                allowFiles ? JFileChooser.FILES_AND_DIRECTORIES : JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);

        if (initDir != null && !initDir.isEmpty()) {
            File initDirFile = new File(initDir);
            if (initDirFile.isDirectory() || (allowFiles && initDirFile.isFile())) {
                fileChooser.setSelectedFile(initDirFile);
            }
        }

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

Related

  1. createUserDefinedProfileFileChooser()
  2. directoryFetch(File starting)
  3. exportFile(JFileChooser fileChooser, String contents)
  4. fileChooser()
  5. getChoiceFileFromUser()
  6. getDriveDisplayName(File path)
  7. getExtension(File f)
  8. getFile()
  9. getFile(Component parent, String title, boolean write)