JFileChooser choose File Or Directory - Java Swing

Java examples for Swing:JFileChooser

Description

JFileChooser choose File Or Directory

Demo Code

/*//from   w  w w.ja va2s .co  m
 * Copyright (C) 2011 NATSRL @ UMD (University Minnesota Duluth, US) and
 * Software and System Laboratory @ KNU (Kangwon National University, Korea) 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class Main {
    private static String chooseFileOrDirectory(String currentPath,
            String dialogTitle, int mode, FileFilter[] filters,
            int dialogType) {
        JFileChooser chooser = new JFileChooser();
        if (filters != null) {
            for (FileFilter f : filters) {
                chooser.addChoosableFileFilter(f);
            }
        }
        chooser.setCurrentDirectory(new java.io.File(currentPath));
        chooser.setDialogTitle(dialogTitle);
        chooser.setFileSelectionMode(mode);
        chooser.setAcceptAllFileFilterUsed(false);
        // open dialog
        if (dialogType == 1) {
            if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                return chooser.getSelectedFile().getAbsolutePath();
            }
        } else {
            // save dialog
            if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                return chooser.getSelectedFile().getAbsolutePath();
            }
        }
        return null;
    }
}

Related Tutorials