Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import javax.swing.*;

import java.awt.*;
import java.io.File;

public class Main {
    /**
     * opens a FileChooser to select a file or folder if a folder is selected a
     * default filename is appended
     *
     * @param c        parent
     * @param fileName default file name (in case a folder is selected)
     * @return null if nothing got selected, otherwise the absolute path
     */
    @SuppressWarnings("SameParameterValue")
    public static String openFileOrDirectoryWithDefaultFileName(Component c, File currentDirectory,
            String fileName) {
        File file = openJFileChooser(c, currentDirectory, JFileChooser.FILES_AND_DIRECTORIES, null);
        if (file == null) {
            return null;
        }
        String path = file.getAbsolutePath();
        if (file.isDirectory()) {
            if (path.endsWith(File.separator)) {
                path = path + fileName;
            } else {
                path = path + File.separator + fileName;
            }
        }
        return path;
    }

    /**
     * opens a file using a JFileChooser
     *
     * @param c          parent
     * @param mode       selection Mode {@link JFileChooser}
     * @param buttonText buttonText, uses "Open" when null ({@link JFileChooser})
     * @return File
     */
    @SuppressWarnings({ "SameParameterValue", "WeakerAccess" })
    public static File openJFileChooser(Component c, File currentDirectory, int mode, String buttonText) {
        JFileChooser fc = new JFileChooser(currentDirectory);
        fc.setFileSelectionMode(mode);
        int result;
        if (buttonText != null) {
            result = fc.showDialog(c, buttonText);
        } else {
            result = fc.showOpenDialog(c);
        }
        if (result == JFileChooser.APPROVE_OPTION) {
            return fc.getSelectedFile();
        }
        return null;
    }
}