Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

public class Main {
    /**
     * 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;
    }
}