Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - Save using JFileChooser with pre-populated file name?

I am trying to make saving and loading easier for some GUIs that I've made, and I would like to be able to pre-populate a filename for the user on save.

Getting the JFileChooser to point at a convenient directory is easy enough, but pre-populating the name doesn't seem so easy. Currently, my code is:

JFileChooser f = new JFileChooser();
f.setSelectedFile(new File(generateName()));

This actually appears to work at first: The filename is populated in the JFileChooser, but when clicking the save button, the chooser just switches file view mode to that of the filename to be saved (if you don't understand, you just have to try it and see). This is likely due to the fact that the file its pointing to doesn't exist yet.

If the user changes the file name and tries to save, it works, but that defeats the whole point.

I was looking for a way to simply setText in the field, but it doesn't seem to have any intuitive access. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Works fine for me. I modified the FileChooserDemo example from the Swing tutorial on "How to Use File Choosers" and it displays the name properly.

fc.setSelectedFile( new File("save.txt")); // added this line
int returnVal = fc.showSaveDialog(FileChooserDemo.this);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...