How do I set a suggested file name using JFileChooser.showSaveDialog(...)?

JavaSwingJfilechooser

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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).

Solution 2 - Java

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.

Solution 3 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyanchenkoView Question on Stackoverflow
Solution 1 - Javabruno condeView Answer on Stackoverflow
Solution 2 - JavaErik MartinoView Answer on Stackoverflow
Solution 3 - JavaAaron DigullaView Answer on Stackoverflow