65

The JFileChooser seems to be missing a feature: a way to suggest the file name when saving a file (the thing that usually gets selected so that it would get replaced when the user starts typing).

Is there a way around this?

TylerH
  • 20,816
  • 57
  • 73
  • 92
yanchenko
  • 55,355
  • 33
  • 144
  • 163

3 Answers3

116

If I understand you correctly, you need to use the setSelectedFile method.

JFileChooser jFileChooser = new JFileChooser();
jFileChooser.setSelectedFile(new File("fileToSave.txt"));
jFileChooser.showSaveDialog(parent);

The file doesn't need to exist.

If you pass a File with an absolute path, JFileChooser will try to position itself in that directory (if it exists).

TylerH
  • 20,816
  • 57
  • 73
  • 92
bruno conde
  • 47,131
  • 14
  • 97
  • 117
  • However, if you're in `DIRECTORIES_ONLY` mode, then this doesn't work. I don't see a way to set the default name of a new directory. – MasterHD Sep 22 '21 at 20:49
4

setSelectedFile doesn't work with directories as mentioned above, a solution is

try {
    FileChooserUI fcUi = fileChooser.getUI();
    fcUi.setSelectedFile(defaultDir);
    Class<? extends FileChooserUI> fcClass = fcUi.getClass();
    Method setFileName = fcClass.getMethod("setFileName", String.class);
    setFileName.invoke(fcUi, defaultDir.getName());
} catch (Exception e) {
    e.printStackTrace();
}

Unfortunately, setFileName is not included in the UI interface, thus the need to call it dynamically. Only tested on Mac.

TylerH
  • 20,816
  • 57
  • 73
  • 92
Erik Martino
  • 3,833
  • 1
  • 18
  • 11
1

If that doesn't work, here is a workaround:

dialog.getUI().setFileName( name )

But you should check whether the selection mode is FILES_ONLY or FILES_AND_DIRECTORIES. If it's DIRECTORIES_ONLY, then setSelectedFile() will strip the file name.

Aaron Digulla
  • 310,263
  • 103
  • 579
  • 794
  • How would you access the dialog though? It's private, created on the spot in `showSaveDialog()`, and disposed immediately after it was shown, still inside that function. – Nyerguds Aug 12 '11 at 08:26