JFileChooser Filters

I have set up a couple of FileFilters to filter files in a JFileChooser and it works great. I only see the files that match a certain extension. With that said, is there a way to determine which filter was currently selected when retrieving the selected file from the FileChooser? If a user was filtering on ".xml" files, I would like to know the .xml filter was selected so I could add the .xml extension for them if they did not specify it.
Thanks

Don't take this personally but
RTFM!
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JFileChooser.html#getFileFilter()

Similar Messages

  • JFileChooser File Filtering

    Why is the FileFilter class for the JFileChooser an abstract class?
    How easy would it have been for Sun to do the following (see code below)?
    It would certainly save on code bloat and make file handling programs just that little more compact, which is especially important when deploying applets or JWS applications.
    Yes I know this code does not handle groups of file extentions. But thats not hard by using another constructor with an ArrayList or somthing.
    * Sets up a file filter to be asociated with the JFileChooser.
    public class FileFiltering extends FileFilter
      String description;
      String extention;
      //============================================================================
       * The constructor for the FileFiltering object.
       * @param extention The file extention to be allowed.
       * @param description A description of the filter.
      //============================================================================
      public FileFiltering(String extention, String description)
        this.extention = extention;
        this.description= description;
      }//===========================================================================
    //=============================================================================
       * A required method of the parent class.
       * @param f The file to be filtered.
       * @return If the file is to be displayed return true. else return false.
    //=============================================================================
      public boolean accept(File f)
          String name = f.getName();
          int i  =name.lastIndexOf(".");
          String extention =  name.substring(i);
          //if the file extention maches that of the class
          if (extention.equalsIgnoreCase(this.extention))
              return true;
      }//===========================================================================
      //============================================================================
       * Returns a description so that the fileChooser can display it in its
       * file type comboBox.
       * @return
      //============================================================================
      public String getDescription()
             return description;
      }//===========================================================================
    }//end of class-===================================================================

    Code for a FileFilter. accept() method that rejects only ".class" files where name contains a $ character
    public boolean accept(File f) {
         if(f==null)
              return false;
         if(f.isDirectory())
               return true;
         String suffix=f.getName().toLowerCase();
         if(suffix.endsWith(".class") && indexOf('$')!=-1)
              return false; //Its a classfile and the name contains the $ char
         return true;

  • Changing filters in jfilechooser causes selection to disapear

    i am hoping you guys can help me.
    i have a JFileChooser with some custom filters. i set a default file to export
    this.setSelectedFile(new File(session.getLabel()+((ExportFileFilter)getFileFilter()).getExtension()));
    this is fine in teh constructor, i get a nice filename derieved form the session.
    but then i use the file type dropdown to select adifferent filter.
    and the filename field goes blank.
    i had attached a property change listener to the filter list, and repeated that command form above in teh propertyChange method. but that didn't help.
    anyone have thoughts?

    Would it be an option to use text boxes from a stencil instead of creating them from scratch?
    Then you could protect them from formating. Or even better just the show line / or geometry.
    If you have to work on existing drawings without protected text boxes, then you could think about a way to select them and protect them by code.
    This selection could be done in the worse case by selecting them by hand, then running the macro.
    HTH,
    Yacine

  • Opening file using JFileChooser with File filtering

    ok guys I am trying set a file filter object to my file chooser it compile but i have a run time error, the error says:
    Exception in thread "AWT-EventQueue-0" java.land.IllegalArgurmentException: Extension must be non-null and not empty
    at javax.swing.filechooser.FileNameExtensionFilter..........
    I have declared
    JFileChooser jfc = new JFileChooser();
    as a global variable
    and in to my ActionListener, ActionPerform the following:
    ActionListener listener = new ActionListener()
              String selection, file, copy;
         public void actionPerformed(ActionEvent e)
    int tipe =0, size = 16;
         String Stile = " ";
         if (e.getSource() == openItem)
              FileNameExtensionFilter filter = new FileNameExtensionFilter("txt");
    jfc.setFileFilter(filter);
              jfc.showOpenDialog(null);
              try
              File f = jfc.getSelectedFile();
              String file = f.getAbsolutePath();
              File f2 = new File(file);
              BufferedReader in = new BufferedReader(new FileReader(f2));
              String text = "";
    String textl = text;
    while( text != null)
                   text = in.readLine() ;
                   textl = textl + text + "\n";
                   System.out.println(text);
    Can some one please tell me whats wrong? and if possible how to fix it? Thank you guys

    A couple of things might help:
    It's a good idea to post the entire stack trace (even though it may appear a bit long). Specifically it helps to know which line in your code triggered the runtime error. You read the stack trace down from the top and the first line you find belonging to your code is a good place to begin looking hard at.
    Another debugging technique is the SSCCE. The idea with this is that you come up with a really brief example illustrating your problem. (ie it compiles, runs and spits out the runtime error). It can be made brief by getting rid of anything extraneous to the problem. A bare button in a frame which when clicked sets up and displays the file chooser should be enough. I describe this as a debugging technique because in the course of constructing such things I often find I isolate - and therefore can see and fix - an error.
    Anyway, sorry this is so general. Maybe someone will come along with a "missing semicolon in line 3"-type solution but, if not, it may be useful.

  • How to add filters to JFileChooser?

    Hi there,
    having slight problems with the Jfilechooser component in my GUI. I would like the Jfilechooser to only show files with the ".java" extension (therefore i can see all ther other java files)
    How can this done?
    thank you.
    raz

    import java.swing.filechooser.FileFilter;
    import java.io.File;
    public class ExtensionFilter extends FileFIlter {
        private String description;
        private String extension;
        public ExtensionFilter(String ext, String, desc) {
            extension = ext.toLowerCase();
            description = desc;
        public boolean accept(File file) {
            return (file.isDirectory() || file.getName().toLowerCase().endsWith(extension));
        public String getDescription() {
            return description;
    ExtensionFilter = someFIlter(".blah" "Example extension (*.blah)");
    yourJFileChooser.addChoosableFileFilter(someFilter);
    yourJFileChooser.setFileSilter(someFilter);

  • How can I get an extension from a file...in JFileChooser

    I have got a problem here. Here I have a JFileChooser, I want to add in
    a FileFilter, and user could only see some type of file. But as long as I
    try to get the extension....It wont compile, could any one teach me how
    to get the extension of a file in JFILECHOOSER???
    ============================================
    import java.io.*;
    import java.io.File.*;
    import javax.swing.filechooser.FileFilter;
    public class MainFrame extends JFrame implements ActionListener {
    public MainFrame() {.............}
    private boolean chooseFile()
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
    FileChoser filtering = new FileChoser("txt");
    fileChooser.setFileFilter(filtering);
    fileChooser.addChoosableFileFilter(filtering);
    int selection = fileChooser.showOpenDialog( this );
    if ( selection == JFileChooser.CANCEL_OPTION )
    return false;
    if (selection == -1) {
    return false;
    File tmpfile = fileChooser.getSelectedFile();
    filename = tmpfile.toString();
    setTitle( "Smiggin Holes 2010 - " + filename );
    return true;
    static class FileChoser extends javax.swing.filechooser.FileFilter
    String extension;
    String description;
    public FileChoser(String extension, String description){
    this.extension = extension;
    this.extension = description;
    // Accept all directories and all gif, jpg, or tiff files.
    public boolean accept(File f)
    if (f != null)
    if (f.isDirectory())
    return true;
    String ext = getExtension(f); //<<<<<<<<<<<THE PROBLEM IS HERE WHEN I TRY TO GET THE EXTENSION OF THE FILE. IT CANT COMPILE
    System.out.println("aasdfasdf"+ext);
    if ((ext!=null)&&(ext.equals(extension)))
    return true;
    return false;
    // The description of this filter
    public String getDescription() {
    return "Just Text Files";
    ======================================
    Could you tell me what can I do? To get the extension of the file selected by the user?
    And What do I have to change?
    Regards,

    Hi,
    can you post your compile error and the code of getExtension().
    Regards
    Ldinka

  • How do I add a filter in JFileChooser for files with no extension?

    Is it possible to have a filter with that filters out files with no extension in a JFileChooser?
    Any help is appreciated.
    Shankar

    When you override accept(File), get the filename from the File object, and parse out the extension. I don't remember there being an easy way to get the extension besides looking for a dot and parsing. If there's no extension, accept it.

  • JFileChooser - File save as

    Hi,
    I have a method in my application called "export" which exports the JPanel content into a file.
    I used the JFileChooser to let the users choose their desired location for saving the file.
    The problem is unless user explicitly types in the file format, it saves the file with no extension.
    How can I have formats like jpg, png in the File Type drop down menu.
    The code is on a different computer, so dont worry about syntax errors, I just write the important bits:
    JFileChooser jfc = new JFileChooser();
    int answer = jfc.showSaveDialog(this);
    if(answer==jfc.APPROVE_OPTION) {
       try {
          File file = jfc.getSelectedFile();
          ImageIO.write(Graph, "png", file); //Graph is what that needs to be exported 
       } catch () {}any help, highly appreciated, thanks

    TheParthian wrote:
    still got the problem,
    I implemented the FileFilter and its two methods, but what I get in the menu is the string i used in the getDescription method.Yeah, that's what the description is meant for.
    what if i want to include more than one extension?Add more filters.
    Also, even if I choose that as the file type, it still saves it with no extension. Do I need to get the string from the menu and add it
    manually to the end of file name?Yes, of course. (That is, you get the selected filter, determine the appropriate extension and add it, if the user did not explicitly specify an extension.)
    BTW - why did you start a new thread? You could have continued in your old one http://forums.sun.com/thread.jspa?threadID=5334819&messageID=10440802#10440802.

  • Problem in JFileChooser

    I have got a problem here. Here I have a JFileChooser, I want to add in
    a FileFilter, and user could only see some type of file. But as long as I
    try to get the extension....It wont compile, could any one teach me how
    to get the extension of a file in JFILECHOOSER???
    ============================================
    import java.io.*;
    import java.io.File.*;
    import javax.swing.filechooser.FileFilter;
    public class MainFrame extends JFrame implements ActionListener {
    public MainFrame() {.............}
    private boolean chooseFile()
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
    FileChoser filtering = new FileChoser("txt");
    fileChooser.setFileFilter(filtering);
    fileChooser.addChoosableFileFilter(filtering);
    int selection = fileChooser.showOpenDialog( this );
    if ( selection == JFileChooser.CANCEL_OPTION )
    return false;
    if (selection == -1) {
    return false;
    File tmpfile = fileChooser.getSelectedFile();
    filename = tmpfile.toString();
    setTitle( "Smiggin Holes 2010 - " + filename );
    return true;
    static class FileChoser extends javax.swing.filechooser.FileFilter
    String extension;
    String description;
    public FileChoser(String extension, String description){
    this.extension = extension;
    this.extension = description;
    // Accept all directories and all gif, jpg, or tiff files.
    public boolean accept(File f)
    if (f != null)
    if (f.isDirectory())
    return true;
    String ext = getExtension(f); //<<<<<<<<<<<THE PROBLEM IS HERE WHEN I TRY TO GET THE EXTENSION OF THE FILE. IT CANT COMPILE
    System.out.println("aasdfasdf"+ext);
    if ((ext!=null)&&(ext.equals(extension)))
    return true;
    return false;
    // The description of this filter
    public String getDescription() {
    return "Just Text Files";
    ======================================
    Could you tell me what can I do? To get the extension of the file selected by the user?
    And What do I have to change?
    Regards,

    Hi !
    in the FileChoser class, the public boolean accept(File f) method can be written like this :
    public boolean accept(File f) {
    if (f.isDirectory || f.getName().endsWith(".txt")) { // you can add other extensions
    return true;
    else {
    return false;

  • JFileChooser:  setFileName on the UI only works at the first call

    The file name on a JFileChooser extension with two customized file filters is set by the code below when it is called. When the filter is changed by the user, the file name disappears.
    BasicFileChooserUI ui = (BasicFileChooserUI)this.getUI();
    ui.setFileName(NameSuggestion);
    An attempt to restore the name with a listener is not working:
    public void propertyChange(PropertyChangeEvent e) {
    if (e.getPropertyName().equals("fileFilterChanged")) {
    BasicFileChooserUI ui = (BasicFileChooserUI)this.getUI();
    ui.setFileName(NameSuggestion);
    Is it really not working or the name is being erased after the set?
    Thanks.

    Please?

  • Changing the file extension by entering a "?" in JFileChooser

    Hi,
    I've encountered a weird thing in JFileChooser. If you open the chooser, type at least one "?" in the field for the filename and then hit the approve button, the file extension will change to the text you entered as the filename.
    To reproduce this problem, simply launch the JWSFileChooserDemo hit the "Open a File..."-button and as the filename enter something like "?deadbeef". Now click the open button and you will see that the file extension changes to "?deadbeef".
    This is a really strange behaviour in my opinion.
    I'm using Windows 7 with java 6u16, but the issue is the same on windows xp sp3. Perhaps on linux too. I'll give it a try as soon as I can.
    Has anyone else encountered that problem?
    Best regards
    Edited by: Wurstsalat on Mar 23, 2010 10:30 AM

    To reproduce this problemThis is not a problem but rather a feature. I did not know of this till now. Thanks for informing.
    As Kevin pointed out this is related to filtering of files.
    ?deadbeefThis will match all the files which start with any letter followed by "deadbeef". So, ? is a wildcard meaning any one character. Other wildcard can be *, which means any number of characters. Try this:
    *.txt
    a*.txt
    *.jp*g
    ??.txt I don't know other wildcards...
    Thanks!

  • How to use Filters in FileDialog class

    Hi!
    I want to get the open dialog of FileDialog window with filters eg, *.java. Could any one help me out to get the solution....
    Regards
    Shan
    [email protected]

    class MyFileChooser{ 
       JFileChooser fc;
       MyFileChooser(){
          fc = new JFileChooser();
          fc.setFileSelectionMode( JFileChooser.FILES_ONLY );
          fc.setFileFilter(new CustomFileFilter("txt","Text files"));
          fc.setFileFilter(new CustomFileFilter("html","html files"));
          fc.setFileFilter(new CustomFileFilter("java","Java source files"));
       open a a file method(){
       close a a file method(){
       class CustomFileFilter extends javax.swing.filechooser.FileFilter{
          String ext;
          String desc;
          CustomFileFilter(String extension, String description) {
             this.ext = extension;
             this.desc = description;
          public String getDescription(){
             return desc;
          public String getExtension(){
             return ext;
    }

  • Changing L&F for the JFileChooser

    Hi,
    take a look at Sun's bug #4711700. Using the Windows L&F, sometimes the JFileChooser throws a NullPointerException when the constructor is called.
    Apparently, the bug is related to retrieving Windows system icons to be shown in the dialog, so it's probably not there when using a non Windows L&F.
    As my app needs to use the L&F of the host OS, I was thinking about using a workaround like this:
    JFileChooser jfc;
    try {
      jfc = new JFileChooser(...);
    } catch(NullPointerException ex) {
      /* change L&F for file chooser here */
      jfc = new JFileChooser();
    }This may not be very appealing, but it's definitely better than the exception!
    The question is: it possible to selectively change the L&F for the file chooser, without affecting the rest of the components, and how do I do it?

    JFileChooser fileChooser=new JFileChooser();// to choose the file ExampleFileFilter filter = new ExampleFileFilter();// to make file settings
         filter.addExtension("jpeg");
         filter.addExtension("jpg");
         filter.setDescription("Image Format");
         fileChooser.setFileFilter(filter);//new File(".")
         fileChooser.setCurrentDirectory(new File("."));
         int result = fileChooser.showOpenDialog(printFrame);//to open dialog box
         if(result==JFileChooser.CANCEL_OPTION)
                   file=null;
    try this u can solve ur problem and , write example filter class
    //ExampleFilter.java
    import java.io.File;
    import java.util.Hashtable;
    import java.util.Enumeration;
    import javax.swing.filechooser.*;
    public class ExampleFileFilter extends FileFilter {
    private static String TYPE_UNKNOWN = "Type Unknown";
    private static String HIDDEN_FILE = "Hidden File";
    private Hashtable filters = null;
    private String description = null;
    private String fullDescription = null;
    private boolean useExtensionsInDescription = true;
    public ExampleFileFilter() {
              this.filters = new Hashtable();
    public ExampleFileFilter(String extension) {
         this(extension,null);
    public ExampleFileFilter(String extension, String description) {
         this();
         if(extension!=null) addExtension(extension);
         if(description!=null) setDescription(description);
    public ExampleFileFilter(String[] filters) {
         this(filters, null);
    public ExampleFileFilter(String[] filters, String description) {
         this();
         for (int i = 0; i < filters.length; i++) {
         addExtension(filters);
         if(description!=null) setDescription(description);
    public boolean accept(File f) {
         if(f != null) {
         if(f.isDirectory()) {
              return true;
         String extension = getExtension(f);
         if(extension != null && filters.get(getExtension(f)) != null) {
              return true;
         return false;
    public String getExtension(File f) {
         if(f != null) {
         String filename = f.getName();
         int i = filename.lastIndexOf('.');
         if(i>0 && i<filename.length()-1) {
              return filename.substring(i+1).toLowerCase();
         return null;
    public void addExtension(String extension) {
         if(filters == null) {
         filters = new Hashtable(5);
         filters.put(extension.toLowerCase(), this);
         fullDescription = null;
    public String getDescription() {
         if(fullDescription == null) {
         if(description == null || isExtensionListInDescription()) {
              fullDescription = description==null ? "(" : description + " (";
              // build the description from the extension list
              Enumeration extensions = filters.keys();
              if(extensions != null) {
              fullDescription += "." + (String) extensions.nextElement();
              while (extensions.hasMoreElements()) {
                   fullDescription += ", ." + (String) extensions.nextElement();
              fullDescription += ")";
         } else {
              fullDescription = description;
         return fullDescription;
    public void setDescription(String description) {
         this.description = description;
         fullDescription = null;
    public void setExtensionListInDescription(boolean b) {
         useExtensionsInDescription = b;
         fullDescription = null;
    public boolean isExtensionListInDescription() {
         return useExtensionsInDescription;
    try this u can solve ur problem and , write example filter class
    cheers
    nr konjeti

  • Filtering in FileDialog (urgent please)

    Hello everybody,
    I was watching one problem with JFileChooser ( Error: "There is no A drive...." at this forum , as i was
    also facing the same problem. BUT when someone suggested , i tried FileDialog and I could get rid of that
    Error
    BUT now i have problem of filtering file , which was so
    easy in JFileChooser . There is getFilenameFilter() and
    setFilenameFilter(FilenameFilter ft) BUT JAVA-Api
    says that
    "...Filename filters do not function in Sun's reference implementation for Windows 95, 98, or NT 4.0."
    I didnt get it properly. Does it mean that we can filter files
    using FileDialog , if i run on these OS..?
    thanx for ur time and help..
    regds,
    Rajesh

    you can also add Windows 2000 to that.
    I am also facing the same problem. The only workaround is to use the setFile("*.ext")
    -aprajit

  • FileDialog (filtering for certain file extensions)

    I have used JFileChooser in the past and was modifying my code to use FileDialog instead as it looks better, looks like the one used by every other Windows program and takes less code to get the job done. My
    question is how to filter for certain file extensions in FileDialog as you can in JFileChooser. I cannot seem to figure out how to, so any help would be highly appreciated. Thank you.
    P.S. Also if you know how to turn off all files like you can in JFileChooser, that would also be extremely helpful.

    Go to the JFileChooser tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html and skip to the section entitled "Filtering the List of Files". That sounds like it should answer your question.

Maybe you are looking for

  • How to include a variable in a formula calc

    Hi, I need to do some calc formula to help my report but I encounter a problem. I use this formula to erase some data from my channel but the formula don't reconize my variables. R4 = CMax(Ch("[1]/TRAVEL_DISTANCE")) Call DataBlDel("[1]/TRAVEL_DISTANC

  • Getting Error while generate Adobe form

    Hi, I  am new to adobe smartforms, i am getting one error while activate smartform. we need to set anything in SICF setting for Adobe smartform??. i am get error like "this forms refers to external file which is not found in compters.please create co

  • Adding prefix to the dropped onto the droplet file names

    Hi, I am trying to adjust apple sample script to rename bunch of files dropped on a droplet instead of all files in selected folder. Here what I have and it doesn't give me list of the dropped files: Add Prefix-Suffix to File Names This script is des

  • Function Modul for read field label

    hi all i search a function modul for read the field label from data element. Example for data element matnr, i must have field label text material. Thx abap_begin

  • Best Hardware Server Specs for Wsus to run close to 3000 Clients

    Hello Team, I am currently configuring a Wsus server 2012 for my company. I am looking forward to buy a Dell rack server and would like to take your input on what is the best server specs I could go for. I am intending to use a San-box to store Wsus