Two Laptop Bag*
The moose likes Swing / AWT / SWT and the fly likes Setting default name in JFileChooser Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Setting default name in JFileChooser" Watch "Setting default name in JFileChooser" New topic

Setting default name in JFileChooser

Gary McGath
Ranch Hand

Joined: Mar 15, 2003
Posts: 52
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)
else chooser.setSelectedFile(newFile(""));
int option = chooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
targetFile = chooser.getSelectedFile();
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
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 in the File name text field.
Michael Morris

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Gary McGath
Ranch Hand

Joined: Mar 15, 2003
Posts: 52
My code turns out to work fine in Windows. Apparently it's a bug in the Macintosh OS X implementation.
It is sorta covered in the JavaRanch Style Guide.
subject: Setting default name in JFileChooser
Similar Threads
JfileChooser selecting existing file.......?
JFileChooser (Open File Dialog)
problem with JDialog
JFileChooser:file name field becomes blank
JFileChooser Last Path