JFileChooser - Custom file name (create new file)

file-io, java, jfilechooser, save, swing

Solution

Check your `if` condition:

if(f.exists() && getDialogType() == SAVE_DIALOG)

What happens if `f` doesn't exist (which is what you would like to be possible)?

You could try:

if(getDialogType() == SAVE_DIALOG) {
    if(f.exists()) {
        // your overwrite checking
    } else {
        super.approveSelection();
        return;
    }
}

Problem

I may be missing something obvious in the `JFileChooser` API, but when I try and use a `JFileChooser` to save a file, I can only select pre-existing files to save to, not enter a new name and save to that. Is that even possible with a `JFileChooser` or should I be using a different API? I have this code to try and do what I'm attempting: ``` public static File getUserFile() { final SaveFileChooser fc = new SaveFileChooser(); fc.setAcceptAllFileFilterUsed(false); for(FileFilter ch : FileFilterUtils.getAllFilters()) { fc.addChoosableFileFilter(ch); } int option = fc.showSaveDialog(JPad.getFrame()); if (option == JFileChooser.APPROVE_OPTION) { return fc.getSelectedFile(); } return null; } public static class SaveFileChooser extends JFileChooser { private static final long serialVersionUID = -8175471295012368922L; @Override public void approveSelection() { File f = getSelectedFile(); if(f.exists() && getDialogType() == SAVE_DIALOG){ int result = JOptionPane.showConfirmDialog(JPad.getFrame(), "The file exists, overwrite?", "Existing file", JOptionPane.YES_NO_CANCEL_OPTION); switch(result){ case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: return; case JOptionPane.CLOSED_OPTION: return; case JOptionPane.CANCEL_OPTION: cancelSelection(); return; } } } } ```

Original source