FileFilter

cs_BlackWood Messages postés 37 Date d'inscription mardi 15 avril 2003 Statut Membre Dernière intervention 4 octobre 2006 - 25 avril 2003 à 10:15
CoreBreaker Messages postés 540 Date d'inscription dimanche 23 mars 2003 Statut Membre Dernière intervention 5 octobre 2007 - 28 avril 2003 à 18:54
Comment ajouter un filtre de fichier dans un FileDialog ? Comment ça marche ? Il n'existe pas de methode du genre addChoosableFileFilter() comme pour JFileChooser ?

Merci d'avance.

BlackWood

3 réponses

CoreBreaker Messages postés 540 Date d'inscription dimanche 23 mars 2003 Statut Membre Dernière intervention 5 octobre 2007 1
25 avril 2003 à 20:41
//import java.io.*;
import java.io.File;

//import java.util.*;
import java.util.Hashtable;
import java.util.Enumeration;

//import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;

/**
 * A convenience implementation of FileFilter that filters out
 * all files except for those type extensions that it knows about.
 *
 * Extensions are of the type ".foo", which is typically found on
 * Windows and Unix boxes, but not on Macinthosh. Case is ignored.
 *
 * Example - create a new filter that filerts out all files
 * but gif and jpg image files:
 *
 *     JFileChooser chooser = new JFileChooser();
 *     FileChooserControlFilter filter = new FileChooserControlFilter(
 *                   new String{"gif", "jpg"}, "JPEG & GIF Images")
 *     chooser.addChoosableFileFilter(filter);
 *     chooser.showOpenDialog(this);
 *
 * @version 1.00 02/12/2002
 * @author Frédéric Meyer
 */
public class FileChooserControlFilter extends FileFilter
{
  /**
   * Return the extension portion of the file's name .
   *
   * @see FileFilter#accept
   */
  private static String getExtension(File aFile)
  {
    try
    {
      String lFilename= aFile.getName();
    int lIdx= lFilename.lastIndexOf('.');

  return ( lIdx > 0 )?lFilename.substring(lIdx + 1).toLowerCase():null;
  }
  catch(NullPointerException eEx)
  {
    return null;
  }
  }

  private Hashtable mFilters= null;
  private String mFullDescription= null;
  private String mLocalDescription= null;

  /**
   * Creates a file filter. If no filters are added, then all
   * files are accepted.
   *
   */
  public FileChooserControlFilter()
  {
  }

  /**
   * Creates a file filter that accepts the given file type.
   * Example: new FileChooserControlFilter("jpg", "JPEG Image Images");
   *
   * Note that the "." before the extension is not needed. If
   * provided, it will be ignored.
   *
   * @see #addExtension
   */
  public FileChooserControlFilter(String aExtension, String aDescription)
  throws Exception
  {
    this();

    addExtension(aExtension);
    setDescription(aDescription);
  }

  /**
   * Return true if this file should be shown in the directory pane,
   * false if it shouldn't.
   *
   * Files that begin with "." are ignored.
   *
   * @see #getExtension
   * @see FileFilter#accepts
   */
  public boolean accept(File aFile)
  {
    try
    {
      if( aFile.isDirectory() )
        return true;
      else if( !(aFile.exists() && aFile.isFile() && aFile.canRead()) )
        return false;
    }
    catch(NullPointerException eEx)
    {
    }

    try
    {
      String lExtension= getExtension(aFile);

      return mFilters.get(lExtension) != null;
    }
    catch(NullPointerException eEx)
    {
      return true;
    }
  }

  /**
   * Adds a filetype "dot" extension to filter against.
   *
   * For example: the following code will create a filter that filters
   * out all files except those that end in ".jpg" and ".tif":
   *
   *   FileChooserControlFilter filter = new FileChooserControlFilter();
   *   filter.addExtension("jpg");
   *   filter.addExtension("tif");
   *
   * Note that the "." before the extension is not needed and will be ignored.
   */
  public void addExtension(String aExtension) throws Exception
  {
    boolean lAddFlag= false;
    
    try
    {
      lAddFlag= aExtension.length() > 0;
    }
    catch(NullPointerException eEx)
    {
    }

    try
    {
      if( lAddFlag )
      {
        mFilters.put(aExtension.toLowerCase(), this);
        mFullDescription= null;
      }
    }
    catch(NullPointerException eEx)
    {
      mFilters= new Hashtable();
      mFilters.put(aExtension.toLowerCase(), this);
      mFullDescription= null;
    }
  }

  /**
   * Returns the human readable description of this filter. For
   * example: "JPEG and GIF Image Files (*.jpg, *.gif)"
   *
   * @see #setDescription
   * @see FileFilter#getDescription
   */
  public String getDescription()
  {
    if( mFullDescription == null )
    {
      boolean lHasDesc= mLocalDescription != null;
      mFullDescription= ( lHasDesc )?mLocalDescription:"";

  		// build the description from the extension list
  	Enumeration lExtensions;

  	try
  	{
  	  	String lPrefix= null;
  	  	Object lExtension;

  	  	lExtensions= mFilters.keys();

        if( lHasDesc )
          mFullDescription+= " (";

        if( lExtensions.hasMoreElements() )
          mFullDescription+= "*." + lExtensions.nextElement();
        while( lExtensions.hasMoreElements() )
          mFullDescription+= ", *." + lExtensions.nextElement();

        if( lHasDesc )
          mFullDescription+= ")";
    }
    catch(NullPointerException eEx)
    {
      if( !lHasDesc )
        mFullDescription= "*.*";
    }
  }
  
    return mFullDescription;
  }

  /**
   * Sets the human readable description of this filter. For
   * example: filter.setDescription("Gif and JPG Images");
   *
   * @see #getDescription
   */
  public void setDescription(String aDescription) throws Exception
  {
  mLocalDescription= aDescription;
  mFullDescription= null;
}
}


puis...
package updater.ui.controls;

//import java.io.*;
import java.io.File;

//import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JFileChooser;

//import updater.ui.controls.filechooser.*;
import updater.ui.controls.filechooser.FileChooserControlFilter;

public class FilenameChooserControl extends JFileChooser
{
  private static String sCurrentDirectory= ".";

  private static String chooseFilename(JFrame aParent, FileChooserControlFilter aFilter, int aDiologType) throws Exception
  {
    String lRes= null;
    FilenameChooserControl lChooser= new FilenameChooserControl(aFilter, aDiologType);

    if( lChooser.showDialog(aParent, null) == APPROVE_OPTION )
    {
      File lResFile= lChooser.getSelectedFile();

      try
      {
        lRes= lResFile.getPath();
        sCurrentDirectory= lResFile.getParent();
      }
      catch(NullPointerException eEx)
      {
      }
    }

    return lRes;
  }

  public static String chooseFilename(JFrame aParent) throws Exception
  {
    return chooseFilename(aParent, null, JFileChooser.SAVE_DIALOG);
  }

  public static String chooseFilename(JFrame aParent, String aExtension, String aDesciption) throws Exception
  {
    String lRes= chooseFilename(aParent, new FileChooserControlFilter(aExtension, aDesciption), JFileChooser.OPEN_DIALOG);

    try
    {
      String lExtension= "." + aExtension;

      if( (aExtension.length() > 0) && (!lRes.endsWith(lExtension)) )
      {
        int lIdx= lRes.lastIndexOf('.');

        if( lIdx > 0 )
          lRes= lRes.substring(0, lIdx);

        lRes+= lExtension;
      }
    }
    catch(NullPointerException eEx)
    {
    }

    return lRes;
  }

  protected FilenameChooserControl(FileChooserControlFilter aFilter, int aDiologType)
  {
    super(sCurrentDirectory);

    setDialogType(aDiologType);
    resetChoosableFileFilters();
    addChoosableFileFilter(aFilter);
    setFileSelectionMode(JFileChooser.FILES_ONLY);
  }
}


Core Breaker :)
0
cs_BlackWood Messages postés 37 Date d'inscription mardi 15 avril 2003 Statut Membre Dernière intervention 4 octobre 2006 2
28 avril 2003 à 09:02
Merci pour ton source mais il utilise un JFileChooser ! En fait ce que je voulais savoir surtout c'est avec un FileDialog ( C'est exactement pareil, FileDialog est l'awt du swing JFileChooser).

BlackWood
0
CoreBreaker Messages postés 540 Date d'inscription dimanche 23 mars 2003 Statut Membre Dernière intervention 5 octobre 2007 1
28 avril 2003 à 18:54
Désolé j'ai lu trop vite.

Core Breaker :)
0
Rejoignez-nous