Opens a Swing file chooser dialog - Java Swing

Java examples for Swing:JDialog

Description

Opens a Swing file chooser dialog

Demo Code


//package com.java2s;
import java.io.File;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;

public class Main {
    /**/*from  w  w w  .  ja va 2s. co m*/
     * Opens a file chooser dialog
     * @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;
    }
}

Related Tutorials