Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Setting default name in JFileChooser

 
Gary McGath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a JFileChooser dialog, I want the initially displayed file name to be whatever the user chose last, or a default name if no file has been chosen yet. The following code correctly sets the current directory to whatever was selected last, but the file name field is always initially blank. Is there a way to make the dialog show a default file name?
void chooseTargetFile() {
JFileChooser chooser = new JFileChooser();
if (targetFile != null)
chooser.setSelectedFile(targetFile);
else chooser.setSelectedFile(newFile("default.xyz"));
int option = chooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
targetFile = chooser.getSelectedFile();
}
}
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gary,
Your code should do exactly that. Take a look at this simple test:

That pops up a Save file dialog in the working directory and dispalys default.xyz in the File name text field.
Michael Morris
 
Gary McGath
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My code turns out to work fine in Windows. Apparently it's a bug in the Macintosh OS X implementation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic