Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 849
yanchenko Avatar asked Dec 10 '08 16:12

yanchenko


People also ask

How do I select multiple files in JFileChooser?

JFileChooser. setMultiSelectionEnabled(true) − To enable the multiple selection of file.

How do I get files from JFileChooser?

JFileChooser has a method, getSelectedFile(). Which is a File. If you open the dialog with showSaveDialog() you should be able to get the File from that (file. getName()).


2 Answers

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

like image 98
bruno conde Avatar answered Sep 29 '22 19:09

bruno conde


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.

like image 42
Erik Martino Avatar answered Sep 29 '22 19:09

Erik Martino