Multiple FileFilter in a JFileChooser

I wanna have a save file dialog with a list of choosableFileFilter that the user can select. Here is my code :
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class ImageFilter extends FileFilter {
    private static String description;
    private static String extension;
    private static String loadOrSave;
    private final static String jpeg = "jpeg";
    private final static String jpg = "jpg";
    private final static String gif = "gif";
    private final static String tiff = "tiff";
    private final static String tif = "tif";
    private final static String png = "png";
    public ImageFilter(String ext,String desc,String type) {
        super();
        extension = ext;
        description = desc;
        loadOrSave = type;
    public boolean accept(File f) {
        if (loadOrSave.equals("load")) { // "load" ==> only accept files with the final extension above
            if (f.isDirectory()) {
                return true;
            String ext = getExtension(f);
            if (ext != null) {
                if (ext.equals(tiff) || ext.equals(tif) || ext.equals(gif) ||
                    ext.equals(jpeg) || ext.equals(jpg) || ext.equals(png)) {
                    return true;
                else return false;
            return false;
        else { // "save" ==> only accept files with extension "extension"
            if (f.isDirectory()) {
                return true;
            String ext = getExtension(f);
            if (ext != null) {
                if (ext.equals(extension)) return true;
                else return false;
            return false;
    // Get the extension of a file.
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');
        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        return ext;
    //The description of the Image filter
    public String getDescription() {
        if (loadOrSave.equals("load")) return "Images (*.jpg,*.jpeg,*.gif,*.png,*.tiff,*.tif)";
        else return description;
    public static String getSaveExtension() {
        if (loadOrSave.equals("save")) return extension;
        else return null;
}I then use my class in the following code fragment :
JFileChooser fc = new JFileChooser(currentdir);
        ImageFilter bmp = new ImageFilter("bmp","Images BMP (*.bmp)","save");
        ImageFilter jpeg = new ImageFilter("jpeg","Images JPEG (*.jpeg)","save");
        ImageFilter jpg = new ImageFilter("jpg","Images JPG (*.jpg)","save");
        ImageFilter png = new ImageFilter("png","Images PNG (*.png)","save");
        ImageFilter wbmp = new ImageFilter("wbmp","Images WBMP (*.wbmp)","save");
        fc.addChoosableFileFilter(bmp);
        fc.addChoosableFileFilter(jpeg);
        fc.addChoosableFileFilter(jpg);
        fc.addChoosableFileFilter(png);
        fc.addChoosableFileFilter(png);
        fc.setAcceptAllFileFilterUsed(false);
        int returnVal = fc.showSaveDialog(fc);The problem is that the choosable FileFilters in the save dialog have the same description : Images WBMP (*.wbmp). I don't understand why. I created different ImageFilters and then add them one by one. So where's the problem ?
Thx in advance.

Damned !
I'm always asking myself if I have to use the static modifier for a class variable.
I don't really understand the concept of static variables...
I think static variables belongs to the class and not to the instances of this class.. Am I right ?

Similar Messages

  • Minor JFileChooser/FileFilter query.

    Ok.
    I've made my own FileFilter. I've integrated this FileFilter with the JFileChooser (using fc.setFileFilter).
    Now, uhm.. so now my JFileChooser's file type drop-down list has 2 entries: "All files" and "MLP files".
    You see now, "MLP files" shows only those files with the extension ".mlp". Is there a way I can show the directories also with the "MLP files" FileFilter?
    Also, is there a way to completely remove the "All files" filefilter, which is the default file filter.

    You can display files and directories using the public static final int FILES_AND_DIRECTORIES
    see this link
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html#FILES_AND_DIRECTORIES
    but the functionality will display all directories, but only the file extensions that you set in the filter will be shown in the directory......
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html
    http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html

  • Active FileFilter in JFileChooser

    Ok, here is my problem:
    I successfully installed 2 TextFilters to my JFileChooser. But unfortunately when i open the JFileChooser Window only the last added FileFilter is active...But i want to start this window with the common file filter (*.*). So how can i set the active FileFilter from beginning?
    here is my Code:
                            fileChooser = new JFileChooser();
                   FileView fv = new ImageFileView();
                   fileChooser.setFileView(fv);
                   fileChooser.setFileFilter(new MyFileFilter(".pdf","Adobe Acrobat files (*.pdf)"));
                   fileChooser.setFileFilter(new MyFileFilter(".rtf","Rich Text Format files (*.rtf)"));
                   fileChooser.showOpenDialog(this);

    i know how to add fileFilter to my JFileChooser...and
    i read the FM!I figured this out in 2 minutes. Was this really so hard?
    private static void JFileChooserTest() {
              JFileChooser chooser = new JFileChooser();
              FileFilter o_filter = chooser.getFileFilter();
              FileExtensionFilter filter = new FileExtensionFilter.HTMLFilter();
              FileExtensionFilter filter2 = new FileExtensionFilter.RTFFilter();
              FileExtensionFilter filter3 = new FileExtensionFilter.TextFilter();
              chooser.addChoosableFileFilter(filter);
              chooser.addChoosableFileFilter(filter2);
              chooser.addChoosableFileFilter(filter3);
              chooser.setFileFilter(o_filter);
              chooser.showOpenDialog(null);
         }

  • JFileChooser problem under Linux

    I am using a JFileChooser component to allow a user to select files for which status information is displayed in my gui.
    I am using a native method to get permissions etc on the choosen file and everything works well. If the user chooses a file which is actually a link or a fifo or a device node or a regular file, everthing works fine - the JFileChooser returns the File selected. I use the File.getPath() function and my native method gives me back permission information for display.
    My problem is when I enable multiple selections in the JFileChooser. For regular files, links, directories it works fine. But if the user try's to select a file which is actually a device node then the JFileChooser won't allow the user to select one.
    Is there any way I can overcome this problem?
    TIA
    Paul

    Hi,
    Windows is completely open and permissible regarding to user permissions. Linux is not. Check if the user you are trying to execute this java file has the permission to open a socket, for example. If he doesn't have it, then an exception would occur.
    Regards,
    Filipe Fedalto

  • FileFilter

    hello people,
    i am trying to write the code for a FileFilter in a JFileChooser, but i'm really having troubles with it... i've searched tutorials and forums, but i didn't find an answer.
    this is my code so far: class myFilter implements FileFilter{
         String fileName;
         Vector listOfFiles = new Vector();
         String z = "myFile.txt";
         public myFilter(){listOfFiles.addElement(z);}
         public boolean accept(File f){
              boolean b = true;
              for (int i = 0; i<listOfFiles.size(); i++){
                   String t = (String)listOfFiles.elementAt(i);
                   if ((f.getName()).equals(t)) b = true;
                   else b = false;
              return b;
         public void addFileName(String n){
              listOfFiles.addElement(n);
         public Vector getList(){
              return listOfFiles;
    }======================
    main:
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new myFilter());
    //...===========================
    it gives me the following error:
    setFileFilter(javax.swing.filechooser.FileFilter) in javax.swing.JFileChooser cannot be applied to (myFilter)
                             chooser.setFileFilter(new myFilter());
    i don't understand what's wrong so any help would be highly appreciated... thanks in advance!

    Your class implements java.io.FileFilter, when it should extend javax.swing.filechooser.FileFilter.

  • JFileChooser Multi file selection problem

    I am using jdk 1.4.2 .
    I tried enabling multiple file selection using JFileChooser but am not able to do so..
    following is the code extract..
    JFileChooser chooser = new JFileChooser();
    int returnVal = chooser.showOpenDialog(RTLogger.this);
    if(returnVal == CougarFileChooser.APPROVE_OPTION)
    chooser.setMultiSelectionEnabled(true);
    if(chooser.isMultiSelectionEnabled())
         System.out.println("multi enabled");//message is displayed
    File [ ] files = chooser.getSelectedFiles();
    System.out.println("the file length is " + files .length);
    //length is zero and not able to select multiple files
    }

    You have to set the option to allow multiple selections before you call showOpenDialog.

  • JFileChooser feature

    Hello all,
    I need to know how could I integrate type-ahead feature into JFileChooser. I have been able to put in FileFilter in the JFileChooser dialog but I cant' seem to figure out how to put in type-ahead feature which causes JFileChooser to jump to a file whose corresponding first letter typed by the user.
            final JFileChooser fc = new JFileChooser (lastDirSelected);
            fc.setDialogTitle("Select Children File");
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
             javax.swing.filechooser.FileFilter fi =   new javax.swing.filechooser.FileFilter () {
              private String des = "Xml Files (*.xml)";
              public boolean accept (File f) {
                String name = f.getName();
                String temp[] = name.split("\\.");
                int length = temp.length;
                String ext = temp[length-1].toLowerCase();
                if (f.isDirectory()){
                  return true;
                if(ext.equals("xml")){
                  return true ;
                } else {
                  return false;
              public String getDescription () {
                return des;
            fc.setFileFilter(fi);
            fc.setApproveButtonText("Select");
            fc.setApproveButtonMnemonic('S');
            int returnVal = fc.showOpenDialog (this);
            if (returnVal == fc.APPROVE_OPTION) {
                childXmlFile = fc.getSelectedFile ().toString ();
                childInfoFileText.setText (childXmlFile);
             }The above code is a working code but there is little problem as well, fc.setApproveButtonMnemonic('S'); does not underline 'S' in "Select". Anyway this issue does not matter to me much, but if anyone of you could get me any solution or advice or suggestion regarding the type-ahead feature, I would be grateful.
    Regards
    Khurram

    http://www.google.com/search?num=100&hl=en&c2coff=1&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=java+typeahead+buffer&spell=1

  • Program not behaving the same after making it a JAR

    Hello,
    I'm developing a program using Eclipse and wanted to export a JAR file to test out. I was able to successfully make the JAR file and it does run, but not as expected. For example, I have the following code which opens up a JFileChooser and lets the user select multiple files to be stored in a JList (via a list model). When I run this from the IDE during development, it works as it should, allowing me to select multiple files from the JFileChooser and adds all of the files to the JList. However, when I run the JAR, it lets the user select multiple files but only adds ONE file to the list. Not only that, but it doesn't seem to be running my "loadComparePaper()" method after adding the item to the list model.
    JFileChooser fileChooser = new JFileChooser();  // New JFileChooser
    fileChooser.setMultiSelectionEnabled( true );     // Allow multiple files to be selected
    FileFilter docFilter = new ExtensionFileFilter( null, acceptableFiles );  // "acceptableFiles" is an array of allowable extensions (not shown in this snippet)
    fileChooser.addChoosableFileFilter( docFilter );  // Tell the JFileChooser to use my filter
    int returnValue = fileChooser.showOpenDialog( null );  // Open the dialog; store result
    if ( returnValue == JFileChooser.APPROVE_OPTION ) {
        File[] selectedFiles = fileChooser.getSelectedFiles();  // Get selected files; store in array
        for ( int i = 0; i < selectedFiles.length; i++ ) {  // For each selected file..
         compareListModel.addElement( selectedFiles[ i ].getName() );  // Add file name to list -- getting stuck here!
         loadComparePaper( selectedFiles[ i ] );  // Call method to load this file (read it)
    }It seems like it's not running the whole for loop, because only one item is being added to the list and it never reaches "loadComparePaper()". Again, it works during development in the IDE and I've tried exporting the JAR quite a few times to see if that was the problem, but the JAR itself is executing.
    Any ideas? I'm baffled as to why it works while I'm testing it out in the IDE, but after I export the JAR it's not working properly. Do you think this has something to do with Eclipse? Has anyone else experienced a problem like this?
    Thanks

    ThomYork:
    Thank you for the advice. I'm new to using JARs and foolishly forgot or didn't realize that I should run it from the console to check for errors. Well, it seems this is the problem: I'm using Apache's POI package and have it stored in the directory +/my_project/lib/poi/+. Within the +/poi/+ folder are 3 JAR files that my program references. When I run my app from within the IDE, I don't get any errors because I've included them in the build path. However, when I run my JAR, it can't find the classes -- it doesn't seem to be looking in the +/lib/poi/+ folder even though my JAR file is in the same root directory as the main class when I run it within the IDE (i.e., both my_main_class and my_main_jar are in the same level directory, and would need to look in the +/lib/poi/+ folder for the other packages).
    So I guess my problem is... my JAR file doesn't "see" the path of the other packages I'm using. In Eclipse, I've configured my project to include these other packages in the build path (and also the "Order and Export" build path) so I thought it would include them, but that doesn't seem to be working.
    Am I missing something? How do I include JARs in other packages / folders so that they work in my JAR?
    Thanks again
    EDIT: I see some other people on this forum experiencing similar issues and I noticed you've helped them out. I tried creating a manifest file, but that didn't work, either... just to be more specific, this is the error message I'm getting:
    Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/apache/poi/poifs/filesystem/POIFSFileSystem
            at OneToOne.loadSourcePaper(OneToOne.java:907)Edited by: ibanezplayer85 on Aug 14, 2008 10:19 PM

  • JfileChooser multiple file selection

    hi everyone....
    i have an aplication with a Jfile chooser coded like this:
    var chooser = new JFileChooser();
    chooser.addChoosableFileFilter(
      FileFilter {
        override function getDescription() {
          "Video {extensions.toString()}"
        override function accept(file) {
          if (file.isDirectory())
            return true;
          def name = file.getName().toLowerCase();
          for (extension in extensions)
            if (name.endsWith(extension))
              return true;
          return false
    chooser.setAcceptAllFileFilterUsed(false);and a image that calls the file chooser like this:
    ImageView {//load button
                var image = 0;
                image : bind boton1[image]
                transforms : bind [Transform.translate(0,770),
                                   Transform.scale(0.7,0.6),]
                onMouseClicked: function( e ) {
                if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(null)) {
                    source = chooser.getSelectedFile().toURI().toString(); }
                                              }but now i want set the file chooser for multiple file selections and save those urls in to an array...
    i added: //chooser.setMultiSelectionEnabled(true); and tried to save in to an array: insert chooser.getSelectedFiles()toString(); into myarray
    but it only delivers unexpected data that can be readed...
    please helpme with this one....
    Already Thanks...
    Edited by: darwinbotlee on 27/02/2010 06:40 PM

    Hi, change the insert statement:
      var a = for(f in chooser.getSelectedFiles()) {
            f.getName();
    insert a  into myarray ;   

  • JFileChooser Multiple selection not working on Mac using apple, command key

    I am using Java 1.4 webstart on Mac machine.
    The code is :
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(2);
    fileChooser.setMultiSelectionEnabled(true);
    Once the File dialog opens I have problems in selecting random multiple files. Apple key or command key is used for random selection on Mac. When using either of these keys multiple selection is not possible. Whereas I am able to select files using the shift key by which row selection is possible.
    If this is not a bug and some code changes are to be done it would be fine if somebody can help me out in this.
    If this is a bug in Java 1.4 and is this fixed in Java 1.5?

    All EIDE / ATA (Parallel) devices (drives, opticals) allowed for two such drives or devices on one bus. The old style was "master" and "Slave" but CS is a "smart" approach, however, the master or only device must be on the end position. Also, the end connector will be black, the middle (slave) is gray.
    Eject sends signal to master
    To eject the "slave" device you use a modifier key.

  • JFileChooser Multiple selection not working on Mac using apple key

    I am using Java 1.4 webstart on Mac machine.
    The code is :
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(2);
    fileChooser.setMultiSelectionEnabled(true);
    Once the File dialog opens I have problems in selecting random multiple files. Apple key is used for random selection on Mac. When using the apple key multiple selection is not possible. Whereas I am able to select files using the command key by which row selection is possible.
    If this is not a bug and some code changes are to be done it would be fine if somebody can help me out in this.
    If this is a bug in Java 1.4 and is this fixed in Java 1.5?

    All EIDE / ATA (Parallel) devices (drives, opticals) allowed for two such drives or devices on one bus. The old style was "master" and "Slave" but CS is a "smart" approach, however, the master or only device must be on the end position. Also, the end connector will be black, the middle (slave) is gray.
    Eject sends signal to master
    To eject the "slave" device you use a modifier key.

  • JFileChooser/Selecting multiple files

    All,
    I'm using the JFileChooser object in 1.4.1_02. Using the multiselection option, I'm allowed to select multiple files. However, when I scroll to the right in the JFileChooser dialog and select more files, the file chooser always returns to the beginning of the list. The files I selected to the right are chosen, but for me to select more files that are displayed to the right, then I need to rescroll back to the right. Is there a setting that I'm not doing? Has anyone else seen this problem?
    Thanks,
    Van Williams

    From the Mac Help selection in the Finder's Help menu:
    Selecting items</b?
    In the Finder and other applications, you can select items in several ways.
    1. Click to select a single item. Drag to select a group of items.
    2. Press the Shift key and click other items to include them in the selection. Click a selected item to deselect it.
    3. To select multiple items in a list that are not next to one another, press the Command key and click the items you want. Click a selected item again to deselect it.
    To "copy" items rather than "move" them you can select the items then press COMMAND-C. Open the Finder window on the desired destination location and then press COMMAND-V to paste.

  • Filefilter for jfilechooser --Confused-

    JFileChooser JFC=new JFileChooser();
    JFC.setFileFilter(new ExeFileFilter());
    class ExeFileFilter implements FileFilter
    {          public boolean accept(File TheFile)
              if(TheFile.getName().endsWith("exe"))
              return true;
         return false;
    }the above code doesnt work, tried several possibilities
    can anyone help me??

    what i want is that the JFilechooser show only exe
    file..
    helpdid you read the examples in JFilechooser Tutorial?
    all you have to do is modify to it.
    here's the code:
    ImageFilter Class
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class ImageFilter extends FileFilter {
        //Accept all directories and all gif, jpg, tiff, or png files.
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            String extension = Utils.getExtension(f);
            if (extension != null) {
                if (extension.equals(Utils.tiff) ||
                    extension.equals(Utils.tif) ||
                    extension.equals(Utils.gif) ||
                    extension.equals(Utils.jpeg) ||
                    extension.equals(Utils.jpg) ||
                    extension.equals(Utils.png)) {
                        return true;
                } else {
                    return false;
            return false;
        //The description of this filter
        public String getDescription() {
            return "Just Images";
    }Utils Class
    import java.io.File;
    import javax.swing.ImageIcon;
    /* Utils.java is used by FileChooserDemo2.java. */
    public class Utils {
        public final static String jpeg = "jpeg";
        public final static String jpg = "jpg";
        public final static String gif = "gif";
        public final static String tiff = "tiff";
        public final static String tif = "tif";
        public final static String png = "png";
         * Get the extension of a file.
        public static String getExtension(File f) {
            String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');
            if (i > 0 &&  i < s.length() - 1) {
                ext = s.substring(i+1).toLowerCase();
            return ext;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = Utils.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
    }

  • Is it possible to add multiple extensions to a filefilter ?

    Hello :
    I'd want to do something like this :
    FileFilter filter = new FileNameExtensionFilter("Various extensions", "jpg, gif, eps");
    FileFilter filter = new FileNameExtensionFilter("Various extensions", "jpg; gif; eps");
    But It does not work ....
    I know I can make a subclass of filter, but I ask if can be possible to do a simple filter like the examples
    Thanks

    tonnot wrote:
    Hello :
    I'd want to do something like this :
    FileFilter filter = new FileNameExtensionFilter("Various extensions", "jpg, gif, eps");
    FileFilter filter = new FileNameExtensionFilter("Various extensions", "jpg; gif; eps");
    But It does not work ....
    I know I can make a subclass of filter, but I ask if can be possible to do a simple filter like the examples
    ThanksAccording to the JavaDocs it uses varargs to take multiple parameters: Documentation
    So in your example it would be:
    FileFilter filter = new FileNameExtensionFilter("Various extensions", "jpg", "gif", "eps");

  • Using jFileChooser and FileFilter

    I am using a jFileChooser and want to add a file filter to only show .jpg files. I tried using...
    FileFilter filter = new FileFilter();
    filter.addExtension("jpg");
    filter.setDescription("JPG Images");
    fileChooser.setFileFilter(filter);
    fileChooser.showSaveDialog(jPanel1)I get an error saying FileFilter is an abstract. I was wondering how I can successfully filter a jFileChooser. Also, what imports libraries do I need to perform the task. I have looked at sample code and it seems they do their own classes, I want to know how to handle this task using the libraries java provides.

    Here's another way to do it, using an anon. inner
    class:
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileFilter() {
    public String getDescription() { return "Image
    files"; }
    public boolean accept(File f) {
    if(f.isDirectory()) return true;
    if(f.getName().endsWith(".jpg")) return true;
    if(f.getName().endsWith(".png")) return true;
    return false;
    /code]
    I find myself using a lot of anon. inner classes in
    Swing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for