JFileChooser.showSaveDialog(…) - how to set suggested file name

笑着哭i 提交于 2019-11-26 15:57:31

问题


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

Is there a way around this?


回答1:


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.

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




回答2:


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 the setFileName is not included in the UI interface, thus the need to call it dynamically. Only tested on mac.




回答3:


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.



来源:https://stackoverflow.com/questions/356671/jfilechooser-showsavedialog-how-to-set-suggested-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!