Real'sHowTo AddThis Feed Button
Custom Search

Use a File DialogTag(s): AWT


On the Win platform, the setFilenameFilter method don't work. We must use the setFile method instead to set a filter.
import java.awt.*;
public class UseFileDialog {

  public String loadFile
      (Frame f, String title, String defDir, String fileType) {
    FileDialog fd = new FileDialog(f, title, FileDialog.LOAD);
    fd.setFile(fileType);
    fd.setDirectory(defDir);
    fd.setLocation(50, 50);
    fd.show();
    return fd.getFile();
    }

  public String saveFile
      (Frame f, String title, String defDir, String fileType) {
    FileDialog fd = new FileDialog(f, title,    FileDialog.SAVE);
    fd.setFile(fileType);
    fd.setDirectory(defDir);
    fd.setLocation(50, 50);
    fd.show();
    return fd.getFile();
    }

  public static void main(String s[]) {
    UseFileDialog ufd = new UseFileDialog();
    System.out.println
      ("Loading : " 
          + ufd.loadFile(new Frame(), "Open...", ".\\", "*.java"));
    System.out.println
      ("Saving : " 
          + ufd.saveFile(new Frame(), "Save...", ".\\", "*.java"));
    System.exit(0);
    }
}
to work with the full pathname, replace
return fd.getFile();
by
    return fd.getDirectory() + 
           System.getProperty("file.separator") + fd.getFile();
On other plateforms, setFilenameFilter may do the job, then you simply do :
 fd.setFilenameFilter(new FilenameFilter(){
    public boolean accept(File dir, String name){
      return (name.endsWith(".jpg") || name.endsWith(".gif"));
    }
 });

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]