This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes JFileChooser Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "JFileChooser" Watch "JFileChooser" New topic
Author

JFileChooser

Miana Husada
Greenhorn

Joined: Feb 04, 2003
Posts: 7
Hi!
I need help in using JFileChooser.
1.
I want to set the file type so that when the users want to open a file, they can only see <.dat> file.
This is my code:
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new MyFilter());
fc.setAcceptAllFileFilterUsed(false);
class MyFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File file)
{
return file.getAbsolutePath().endsWith (".dat");
}
public String getDescription() {
return "*.dat";
}
}
Problem: file type column has been set in the dialog box, but file chooser can't browse the folder(can't go inside directory and show the desired file).
2.
how to set the save dialog so that user only need to write file name but it is saved by adding the extension also.e.g fileName.dat
Thanks
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Miana,
First off this question should have been posted in the swing forum. But I will take a shot at answering your quetsions here.

Problem: file type column has been set in the dialog box, but file chooser can't browse the folder(can't go inside directory and show the desired file).

You need to change your FileFilter.accept() method to accept directories as well like:




2.
how to set the save dialog so that user only need to write file name but it is saved by adding the extension also.e.g fileName.dat

You need to subclass JFileChooser and override the getSelectedFile() and/or getSelectedFiles() methods as appropriate. Something like this:

Here is a sample test class to do this:

Hope this helps,
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
Miana Husada
Greenhorn

Joined: Feb 04, 2003
Posts: 7
Hi Michael,
thanks for the explanations, it really helps
 
jQuery in Action, 2nd edition
 
subject: JFileChooser
 
Similar Threads
Applet with JFilechooser called from a Javascript blocks paint messages to Browser
JFileChooser problem
problem with file chooser
Applet with JFilechooser called from a Javascript blocks paint messages to Browser
filters with filechooser