Get user-inputed file name from JFileChooser Save dialog box
Asked Answered
E

3

8

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.

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?

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.

Eloign answered 27/5, 2010 at 4:21 Comment(0)
H
15
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

Hamper answered 2/6, 2013 at 20:34 Comment(0)
E
5

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();
Eurhythmics answered 27/5, 2010 at 5:3 Comment(2)
Thank you. I'd just figured that out a few minutes ago, and your answer confirmed it. I'm very grateful.Eloign
No problem. I'm sure you'll do fine! All the best.Eurhythmics
G
3

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

If you open the dialog with showSaveDialog() you should be able to get the File from 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 :) )

Good luck with your assignment.

Greenness answered 27/5, 2010 at 5:1 Comment(1)
Thank you too. =) I love how people here are so clear and prompt. But thank YOU, for showing just how much that's true.Eloign

© 2022 - 2024 — McMap. All rights reserved.