Java JFileChooser.showSaveDialog(...) - 如何设置建议的文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/356671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:47:15  来源:igfitidea点击:

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

javaswingjfilechooser

提问by yanchenko

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

JFileChooser似乎缺少该FEATURE:一种方式保存文件(通常被选中,这样,当用户开始输入将被替换的东西)时,建议的文件名。

Is there a way around this?

有没有解决的办法?

采纳答案by bruno conde

If I understand you correctly, you need to use the setSelectedFilemethod.

如果我理解正确,您需要使用该setSelectedFile方法。

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, JFileChooserwill try to position itself in that directory (if it exists).

编辑:如果您传递带有绝对路径的文件,JFileChooser将尝试将自身定位在该目录中(如果存在)。

回答by Aaron Digulla

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

如果这不起作用,这里有一个解决方法:

dialog.getUI().setFileName( name )

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

但是您应该检查选择模式是否为FILES_ONLYFILES_AND_DIRECTORIES。如果是DIRECTORIES_ONLYsetSelectedFile()则将删除文件名。

回答by Erik Martino

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

setSelectedFile 不适用于上述目录,解决方案是

    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.

不幸的是 setFileName 没有包含在 UI 界面中,因此需要动态调用它。仅在 mac 上测试。