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

大憨熊 提交于 2019-11-27 12:17:11

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

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.

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.

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