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
JFileChooser.showSaveDialog(...) - how to set suggested file name
提问by yanchenko
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).
在JFileChooser
似乎缺少该FEATURE:一种方式保存文件(通常被选中,这样,当用户开始输入将被替换的东西)时,建议的文件名。
Is there a way around this?
有没有解决的办法?
采纳答案by bruno conde
If I understand you correctly, you need to use the setSelectedFile
method.
如果我理解正确,您需要使用该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, JFileChooser
will 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_ONLY
or FILES_AND_DIRECTORIES
. If it's DIRECTORIES_ONLY
, then setSelectedFile()
will strip the file name.
但是您应该检查选择模式是否为FILES_ONLY
或FILES_AND_DIRECTORIES
。如果是DIRECTORIES_ONLY
,setSelectedFile()
则将删除文件名。
回答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 上测试。