import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; /** * shows a SaveFileDialog */ public class SaveFileDialog { private ArrayList<String> _extensiontext = new ArrayList<>(); private ArrayList<String> _extension = new ArrayList<>(); /** * shows SaveFileDialog * @param path initial path, may be null * @return selected file or null if not overwritten */ public File showDialog(String path) { File f = null; if (_extensiontext.size() > 0) { if ((path == null) || (path.length() == 0)) { path = System.getProperty("user.home"); } final JFileChooser c = new JFileChooser(path); c.setDialogTitle("Save file"); c.setDialogType(JFileChooser.SAVE_DIALOG); c.setFileSelectionMode(JFileChooser.FILES_ONLY); // add filters for (int i = 0; i < _extensiontext.size(); i++) { FileNameExtensionFilter ff = new FileNameExtensionFilter(_extensiontext.get(i), _extension.get(i)); c.setFileFilter(ff); } c.setVisible(true); // if "ok" or "yes" pressed if (c.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { f = c.getSelectedFile(); String nameLower = f.getName().toLowerCase(); String[] exts = ((FileNameExtensionFilter)c.getFileFilter()).getExtensions(); boolean hascorrectext = false; // check if filename ends with filterextension for (String ext : exts) { if (nameLower.endsWith('.' + ext.toLowerCase())) { hascorrectext = true; break; } } if (!hascorrectext) { // if not, make new filename f = new File(f.toString() + '.' + exts[0].toLowerCase()); } boolean overwrite = true; // if file exists ask for overwriting if (f.exists()) { overwrite = (JOptionPane.showConfirmDialog(null, "File exists, overwrite?", "Question", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION); } if (!overwrite) { f = null; } } c.setVisible(false); } return f; } /** * adds FileNameExtensionFilter * @param text Filtertext, e.g. "Textfiles (*.txt)" * @param ext Filterextension, e.g. "txt" */ public void addExtension(String text, String ext) { _extensiontext.add(text); _extension.add(ext); } }
Aufruf:
SaveFileDialog fd = new SaveFileDialog(); // add an extension fd.addExtension("Textfiles (*.txt)", "txt"); // open dialog and get selected file File f = fd.showDialog(null);