Java 从 JFileChooser 保存对话框中获取用户输入的文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2918435/
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-13 14:28:46  来源:igfitidea点击:

Get user-inputed file name from JFileChooser Save dialog box

javatextfieldjfilechoosersave-as

提问by Anya

This answer to this question may seem obvious, but I'm actually struggling with it quite a bit. I've searched through JFileChooser methods in the API, and I've looked at some of the questions already asked and answered here on stackoverflow.

这个问题的这个答案似乎很明显,但我实际上在为此苦苦挣扎。我搜索了 API 中的 JFileChooser 方法,并查看了一些已经在 stackoverflow 上提出并回答的问题。

My question is this. In my program, I am to allow the user to type in a file name which I will then use to create a brand new file that I will write on. How do you get the text the user has entered in the textfield next to the label "Save As:" on the Save dialog box provided by JFileChooser? Is there a JFileChooser method that would allow me to get that user-inputed text? Or would I have to go through another class, or do something else to get that text?

我的问题是这个。在我的程序中,我允许用户输入一个文件名,然后我将使用它来创建一个全新的文件,我将在上面写入。如何获取用户在 JFileChooser 提供的“保存”对话框中“另存为:”标签旁边的文本字段中输入的文本?是否有 JFileChooser 方法可以让我获取用户输入的文本?或者我是否必须通过另一堂课,或做其他事情才能获得该文本?

Thank you so much, to anyone who answers. It's very late for me now, and this program is due in a few hours (meaning I'll be having another sleepless night). Desperate may be too strong a word, but I'm something close enough.

非常感谢,感谢所有回答的人。现在对我来说已经很晚了,这个节目将在几个小时后到期(这意味着我将再度过一个不眠之夜)。绝望这个词可能太强烈了,但我已经足够接近了。

回答by Snake

JFileChooser has a method, getSelectedFile(). Which is a File.

JFileChooser 有一个方法,getSelectedFile()。这是一个File

If you open the dialog with showSaveDialog()you should be able to get the Filefrom that (file.getName()). And you can parse that to get the user's entered text. (e.g. drop the extension... I don't know what you want :) )

如果您使用showSaveDialog()打开对话框,您应该能够从中获取文件( file.getName ())。您可以解析它以获取用户输入的文本。(例如删除扩展名...我不知道你想要什么:))

Good luck with your assignment.

祝你任务顺利。

回答by BoltClock

After you've opened the save file dialog and determined that the user wants to save the file, grab the file name with this:

打开保存文件对话框并确定用户想要保存文件后,使用以下命令获取文件名:

String filename = mySaveDialog.getSelectedFile().getName();

回答by Gaurav Sharma

JFileChooser chooser=new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORY_ONLY);
chooser.showSaveDialog(null);

String path=chooser.getSelectedFile().getAbsolutePath();
String filename=chooser.getSelectedFile().getName();

......in filename variable you will get the file name entered by the user

......在文件名变量中,您将获得用户输入的文件名