Java JFileChooser getFile(Component parent, String title, boolean write)

Here you can find the source of getFile(Component parent, String title, boolean write)

Description

Shows a dialog to open/save file (the write parameter steers this).

License

LGPL

Parameter

Parameter Description
parent the parent for the open/save dialog
title the dialog title
write if true the dialog is for saving the file, for opening otherwise

Return

the chosen file as a object, null if not existing or not overwritable

Declaration

public static File getFile(Component parent, String title, boolean write) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.awt.Component;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Main {
    /**/*from  www.  j a va2s .  co  m*/
     * Shows a dialog to open/save file (the write parameter steers this). For
     * opening the file, the existence of the file is checked. For saving the
     * file an overwrite confirmation message is displayed if necessary.
     * 
     * @param parent
     *            the parent for the open/save dialog
     * @param title
     *            the dialog title
     * @param write
     *            if true the dialog is for saving the file, for opening
     *            otherwise
     * @return the chosen file as a {@link File} object, null if not existing or
     *         not overwritable
     */
    public static File getFile(Component parent, String title, boolean write) {
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle(title);
        if (write) {
            fc.showSaveDialog(parent);
        } else {
            fc.showOpenDialog(parent);
        }
        File f = fc.getSelectedFile();
        if (f == null || (!write && !f.exists()) || (f.exists() && !f.isFile()))
            return null;
        if (write && f.exists()) {
            int r = JOptionPane.showConfirmDialog(parent, "File \"" + f.getName() + "\" exists. Overwrite?");
            if (r != 0)
                return null;
        }
        return f;
    }
}

Related

  1. getChoiceFileFromUser()
  2. getDir(String title, String initDir, boolean allowFiles, Component parent)
  3. getDriveDisplayName(File path)
  4. getExtension(File f)
  5. getFile()
  6. getFile(FileFilter filter)
  7. getFile(String initialPath, final String extension, String TitleText)
  8. getFile(String message, boolean isLoadNotSave, File defaultFileOrDir, boolean allowMultipleSelection, String description, final String... extensions)
  9. getFile(String title, File initialDir)