Java examples for Swing:JFileChooser
JFileChooser choose File To Save
/*//from w w w . j a v a 2 s . c o m * Copyright (C) 2011 NATSRL @ UMD (University Minnesota Duluth, US) and * Software and System Laboratory @ KNU (Kangwon National University, Korea) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //package com.java2s; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; public class Main { public static String chooseFileToSave() { return chooseFileToSave(".", "Save as..."); } public static String chooseFileToSave(FileFilter filter) { return chooseFileToSave(".", "Save as...", filter); } public static String chooseFileToSave(String currentPath, String dialogTitle) { return chooseFileOrDirectory(currentPath, dialogTitle, JFileChooser.FILES_ONLY, null, 0); } public static String chooseFileToSave(String currentPath, String dialogTitle, FileFilter filter) { return chooseFileOrDirectory(currentPath, dialogTitle, JFileChooser.FILES_ONLY, new FileFilter[] { filter }, 0); } private static String chooseFileOrDirectory(String currentPath, String dialogTitle, int mode, FileFilter[] filters, int dialogType) { JFileChooser chooser = new JFileChooser(); if (filters != null) { for (FileFilter f : filters) { chooser.addChoosableFileFilter(f); } } chooser.setCurrentDirectory(new java.io.File(currentPath)); chooser.setDialogTitle(dialogTitle); chooser.setFileSelectionMode(mode); chooser.setAcceptAllFileFilterUsed(false); // open dialog if (dialogType == 1) { if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { return chooser.getSelectedFile().getAbsolutePath(); } } else { // save dialog if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { return chooser.getSelectedFile().getAbsolutePath(); } } return null; } }