Java JFrame findFileSave(JFrame frame, String ext, String desc)

Here you can find the source of findFileSave(JFrame frame, String ext, String desc)

Description

find File Save

License

Open Source License

Declaration

public static File findFileSave(JFrame frame, String ext, String desc) 

Method Source Code


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

import java.io.*;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Main {
    public static File findFileSave(JFrame frame, String ext, String desc) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new FileNameExtensionFilter(desc, ext));

        if (chooser.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION) {
            return null;
        }// ww w  .jav  a  2s  .com

        return getSelectedFileWithExtension(chooser);
    }

    /**
     * Returns the selected file from a JFileChooser, including the extension from
     * the file filter.
     * From: http://stackoverflow.com/a/18984561
     */
    public static File getSelectedFileWithExtension(JFileChooser c) {
        File file = c.getSelectedFile();
        if (c.getFileFilter() instanceof FileNameExtensionFilter) {
            String[] exts = ((FileNameExtensionFilter) c.getFileFilter()).getExtensions();
            String nameLower = file.getName().toLowerCase();
            for (String ext : exts) { // check if it already has a valid extension
                if (nameLower.endsWith('.' + ext.toLowerCase())) {
                    return file; // if yes, return as-is
                }
            }
            // if not, append the first extension from the selected filter
            file = new File(file.toString() + '.' + exts[0]);
        }
        return file;
    }
}

Related

  1. enterFullScreenIfPossible(JFrame mainAppFrame)
  2. error(JFrame frame, String msg)
  3. exitFullScreen(JFrame mainAppFrame)
  4. fileChooser(JFrame frame, boolean saveDialog, String windowName, String filterName, String filterExtension)
  5. findFileOpen(JFrame frame, String ext, String desc)
  6. findJFrame(Component c)
  7. findJFrame(Component myComponent)
  8. fitToDesktop(final JFrame frame)
  9. fullScreen(JFrame window)