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;

Similar Messages

  • Set file filters in flex for save, not for browse

    How can i set file filters in flex for save, not for browse?
    Right now i am using filereferce class for saving purpose but i could
    not able to set filter. We can easily do it for browse.

    You can try to delete [http://kb.mozillazine.org/mimeTypes.rdf mimeTypes.rdf] in the [http://kb.mozillazine.org/Profile_folder_-_Firefox Profile Folder]
    * http://kb.mozillazine.org/File_types_and_download_actions#Resetting_download_actions
    Create a new profile as a test to check if your current profile is causing the problems.
    See:
    * [https://support.mozilla.com/kb/Basic+Troubleshooting#w_8-make-a-new-profile Basic Troubleshooting: Make a new profile]
    There may be extensions and plugins installed by default in a new profile, so check that in "Tools > Add-ons > Extensions & Plugins" in case there are still problems.
    If that new profile works then you can transfer some files from the old profile to that new profile (be careful not to copy corrupted files)
    See:
    * http://kb.mozillazine.org/Transferring_data_to_a_new_profile_-_Firefox

  • 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.

  • 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.

  • JFileChooser file filter and view does not display Drive letters

    This code displays only files that end in abc.xml, and directories. For example, "helloabc.xml" and directory "world" will display as hello and world, respectively.
    However, I am surprised to find that the drive letters are not displayed at all. eg. C:
    any insights?
    thanks,
    Anil
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileView;
    public class NoDrive {
         protected static final String ABC_FILE_EXTN = "abc.xml";
         public String selectFile(String function){
              File file = null;
              JFileChooser fc = new JFileChooser();
              fc.setFileFilter(new FileFilter() {
                   public boolean accept(File f) {
                        if (!f.isFile() || f.getName().endsWith(ABC_FILE_EXTN))
                             return true;                    
                        return false;
                   public String getDescription() {
                        return "ABC files";
              fc.setFileView(new FileView() {
                   public String getName(File f) {
                        String name = f.getName();
                        if (f.isFile() && name.endsWith(ABC_FILE_EXTN))
                             return name.substring(0, name.indexOf(ABC_FILE_EXTN));
                        return name;
              int returnVal = fc.showDialog(null, function);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   file = fc.getSelectedFile();
                   return file.getName();
              return null;
         public static void main(String[] args) {
              (new NoDrive()).selectFile("Open ABC");
    }

    OK. Here's the correct code:
        fc.setFileView(new FileView() {
          public String getName(File f) {
            String name = f.getName();
            if (f.isFile() && name.endsWith(ABC_FILE_EXTN)){
              return name.substring(0, name.indexOf(ABC_FILE_EXTN));
            else{
              return super.getName(f);
        });

  • JFileChooser "File Name" field

    Hi,
    I am trying to use a JFileChooser as a component within a JDialog, and everything works fine, except that I do not understand how I can get the value of a filename typed into the "File Name:" field on the form. I've read the "JFileChooser" Java doco about five times and I can't see anything that would give me access to this field. GetName() appears to be a red herring.
    Anyone got any ideas?
    Thanks,
    Tim

    Thanks for your swift reply.
    Unfortunately perhaps I wasn't quite clear - I have added the JFileChooser as a component to a JDialog, not run it standalone via showDialog() or similar.
    I am trying to get the user to select a directory and type a file name that a new file can be saved into.
    Here is the code that displays the chooser:
       private JPanel saveFilePnl(String folder)
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(new JLabel("<html>Select the folder to save the new sequence into,<br>" +
                               "and type in an appropriate File Name:<br>"),"North");
          saveFileChooser.setCurrentDirectory(new File(folder));
          SimpleFileFilter filter = new SimpleFileFilter("xml", "Nucleotide Sequences"); 
          saveFileChooser.setFileFilter(filter);
          saveFileChooser.setControlButtonsAreShown(false);
          saveFileChooser.setBorder(BorderFactory.createCompoundBorder
                                (BorderFactory.createEtchedBorder(),
                                 BorderFactory.createEmptyBorder(8,8,8,8) ));
          panel.add(saveFileChooser, "Center");
          return panel;
    }This panel is added to a card on a CardLayout JDialog. After the user selects a folder and types in a filename I want to verify that they have done so before moving on to the next card. So I need to ensure that there is a name in the "File Name:" field on the chooser.
    Thanks,
    Tim

  • File Filtering in FileDialog on Windows

    We have a Java application that we are deploying primarily on Windows platforms. We use FileDialog to perform a "file save as" function. We would like to filter the list of files shown to match a file extension. Even better, we would like to populate the File Types dropdown on the standard Windows dialog.
    It is well known that FileNameFilter does not work on the Windows platform, so that is not a viable solution.
    We have tried JFileChooser, but performance was intolerable when a directory had many files (many = thousands). (Sure, we can tell the user not do have so many files in directories, but we can't control what the user does so this only leads to bug reports that our application is hung/broken while JFileChooser takes minutes to fill the dialog.)
    This leads me to think that we need a JNI solution for use on Windows (we can use FileNameFilter on other platforms). Are there any low cost implementations available? I'd appreciate any suggestions.
    Thank you.
    Guy

    I have used FileFilter with JFileChooser. Performance was not adequate, as I described in my post. I need a solution which a) works and b) has adequate performance.

  • Can JFileChooser file name field return all entered chars

    In JFileChooser, if I want to get all entered characters from file name field, is there a method I can call?
    I used method chooserUI.getFileName() or chooser.getSelectedFile(). These two methods returned texts which missed back slash and forward slash. I want to get everything what I entered in file name field. I searched and read related JFileChooser topic, but there isn't a topic about this. Can any of you know what I can do?
    Thank you very much.

    JFileChooser isn't for entering text, it's for selecting files. If you put for example "abc/def" in the filename box, it's going to interpret that as "file def in directory abc" and your getFileName() will return "def". (You'll notice that getFileName() doesn't return the directory path, just the filename part of it, right?)

  • JFileChooser file name extention queistion

    hi i would like to know if it is possible to place a file extention in the filename section when you open the save dialog. So as when the user types a file name in the file extention is added automaticly to only allow the user to save in .png. My code is as follows.
    private void screenshot()
              /** currently no dialog to confirm action as remains
              on screen when saving screenshot! **/
              int status;
              JFileChooser fc = new JFileChooser();
              fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              try {
                        Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit ().getScreenSize ());
                        BufferedImage image = new Robot().createScreenCapture(rect);
                        try {
                             fc.addChoosableFileFilter(new PNGFilter());
                            status = fc.showSaveDialog(information);
                            if(status == JFileChooser.APPROVE_OPTION)
                            File selFile = fc.getSelectedFile();
                            ImageIO.write(image, "png", selFile);
                            JOptionPane.showMessageDialog(information, "File saved to "+ selFile);     
                        } catch (IOException e) {
                                  Error.SaveError(e);
                        catch (AWTException e) {
                             Error.AbstractWindowToolkit(e);
    }

    You can always check selFile's name, and if it
    doesn't end with .png replace it
    with a new File with the same name, but with .png
    added on.Thanks for that. I have done just that and it works great now.
    if(getExtension(selFile).equals("NO_EXTENSION"))
                               selFile = new File(selFile.toString() + ".png");
                           }

  • JFileChooser File Name

    Hi!
    I'm using a JFileChooser to save in a local folder a file stored in my database and I'd like to set the File Name when I open the FileChooser, do you know how to do it ??
    Thanks !!
    TLLI

    JFileChooser.setSelectedFile()?

  • Customizing JFileChooser (File Size) Need Help

    Can you help me with this. I want to customize my JFileChooser. I'm in a Windows environment so the file view that I see is same with that of the option pane of windows. What I would like to do is make the size that is viewed from the screen from ##KB to specific bytes size. (ex. 34421245). Can someone help me on this. I was able to see some codes on the net but those codes are not straightforward. They override the BasicFileChooserUI. Can someone help me on this. I don't want to override the BasicFileChooserUI instead I want to use the JFileChooser and change the size from ###KB to bytes. Thank you. ^_^

    Hi Rachel,
    My best idea for that is to load the swf files externally, so
    that each page is a different swf. A technique like this would be
    very simple and quick to use, because it only loads what you need
    when you need it.
    For example, you'd set the intro page to load right away, and
    then when you select "At Work" the intro page unloads and is
    replaced by the at work page.
    Another thing you may want to consider is holding the images
    in an xml file, and then using some basic flash/xml intergration to
    load each image as it's called. That way each image isn't stored in
    the flash file causing it to increase in size, and instead is
    actually loaded externally which is must faster.
    There are some great tutorials, if you're intrested, on how
    to do both of these at:
    http://www.kirupa.com/
    Hope I helped some!

  • JFileChooser file select by doubleclick

    To improve the user friendliness of my custom JFileChooser dialog, I want the user to be able to doubleclick on the file he wants to open, instead of having to click the file and then on open.
    I thought it would be the simplest thing, but have not found any solutions. Adding a mouselistener to the JFileChooser will not return mouse events inside the file list itself, and the PropertyChangeListener does not respond to a double click action either.
    Any help would be greatly appreciated! :-)

    Works automatically in the JFileChoosers in my app (Win2K Pro). Could be the l&f or you are overriding the default mouse actions. A look at the code may help.
    Robert Templeton

  • Nested Zip file filtering

    Hello All 
    I need to find a solution for scanning nested zip files recursively (a .exe in a zip file, in a zip file) on an exchange edge transport server. 
    Our third party exchange antivirus/antispam solution, cannot scan in depth, only the first level of a zip 
    Is there a way for exchange 2013/2007 to remove all executable (exe, scr, bat etc) from inside a zip, inside of a zip file?
    Thanks

    Hi,
    Based on my knowledge, Exchange doesn't have built-in function to scan all executable (exe, scr, bat etc) from inside a zip and remove them. Your understanding will be appreciated.
    Best regards,
    Amy Wang
    TechNet Community Support

  • JFileChooser's approve button text changes when file

    I have a JFileChooser used for loading some XML file(s). We want the approve button's text to be "Load". When I bring up the dialog, the button text initially reads "Load", when I select a directory, it reads "Open", if I select a file again, it goes back to "Load". So far, so good.
    The problem comes when using it in a non-English language. When I bring up the dialog, the button text initially reads the appropriately translated "Load". However, when I select a directory, it changes to the English "Open". I do not see a method to use to adjust this text. Am I missing something, or is this a bug?
    Any help is greatly appreciated.
    Jamie

    Here's some code I'll put into the public domain:
    package com.graphbuilder.desktop;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Stack;
    import java.util.Vector;
    import java.util.StringTokenizer;
    import java.io.File;
    <p>Attempt to improve the behaviour of the JFileChooser.  Anyone who has used the
    the JFileChooser will probably remember that it lacks several useful features.
    The following features have been added:
    <ul>
    <li>Double click to choose a file</li>
    <li>Enter key to choose a file after typing the filename</li>
    <li>Enter key to change to a different directory after typing the filename</li>
    <li>Automatic rescanning of directories</li>
    <li>A getSelectedFiles method that returns the correct selected files</li>
    <li>Escape key cancels the dialog</li>
    <li>Access to common GUI components, such as the OK and Cancel buttons</li>
    <li>Removal of the useless Update and Help buttons in Motif L&F</li>
    </ul>
    <p>There are a lot more features that could be added to make the JFileChooser more
    user friendly.  For example, a drop-down combo-box as the user is typing the name of
    the file, a list of currently visited directories, user specified file filtering, etc.
    <p>The look and feels supported are Metal, Window and Motif.  Each look and feel
    puts the OK and Cancel buttons in different locations and unfortunately the JFileChooser
    doesn't provide direct access to them.  Thus, for each look-and-feel the buttons must
    be found.
    <p>The following are known issues:  Rescanning doesn't work when in Motif L&F.  Some
    L&Fs have components that don't become available until the user clicks a button.  For
    example, the Metal L&F has a JTable but only when viewing in details mode.  The double
    click to choose a file does not work in details mode.  There are probably more unknown
    issues, but the changes made so far should make the JFileChooser easier to use.
    public class FileChooserFixer implements ActionListener, KeyListener, MouseListener, Runnable {
         Had to make new buttons because when the original buttons are clicked
         they revert back to the original label text.  I.e. some programmer decided
         it would be a good idea to set the button text during an actionPerformed
         method.
         private JFileChooser fileChooser = null;
         private JButton okButton = new JButton("OK");
         private JButton cancelButton = new JButton("Cancel");
         private JList fileList = null;
         private JTextField filenameTextField = null;
         private ActionListener actionListener = null;
         private long rescanTime = 20000;
         public FileChooserFixer(JFileChooser fc, ActionListener a) {
              fileChooser = fc;
              actionListener = a;
              fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              okButton.setMnemonic('O');
              cancelButton.setMnemonic('C');
              JButton oldOKButton = null;
              JButton oldCancelButton = null;
              JTextField[] textField = getTextFields(fc);
              JButton[] button = getButtons(fc);
              JList[] list = getLists(fc);
              String laf = javax.swing.UIManager.getLookAndFeel().getClass().getName();
              if (laf.equals("javax.swing.plaf.metal.MetalLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.motif.MotifLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[2];
                   button[1].setVisible(false); // hides the do-nothing 'Update' button
                   button[3].setVisible(false); // hides the disabled 'Help' button
                   filenameTextField = textField[1];
                   fileList = list[0];
              fix(oldOKButton, okButton);
              fix(oldCancelButton, cancelButton);
              okButton.addActionListener(this);
              cancelButton.addActionListener(this);
              fileList.addMouseListener(this);
              addKeyListeners(fileChooser);
              new Thread(this).start(); // note: rescanning in Motif feel doesn't work
         public void run() {
              try {
                   while (true) {
                        Thread.sleep(rescanTime);
                        Window w = SwingUtilities.windowForComponent(fileChooser);
                        if (w != null && w.isVisible())
                             fileChooser.rescanCurrentDirectory();
              } catch (Throwable err) {}
         public long getRescanTime() {
              return rescanTime;
         public void setRescanTime(long t) {
              if (t < 200)
                   throw new IllegalArgumentException("Rescan time >= 200 required.");
              rescanTime = t;
         private void addKeyListeners(Container c) {
              for (int i = 0; i < c.getComponentCount(); i++) {
                   Component d = c.getComponent(i);
                   if (d instanceof Container)
                        addKeyListeners((Container) d);
                   d.addKeyListener(this);
         private static void fix(JButton oldButton, JButton newButton) {
              int index = getIndex(oldButton);
              Container c = oldButton.getParent();
              c.remove(index);
              c.add(newButton, index);
              newButton.setPreferredSize(oldButton.getPreferredSize());
              newButton.setMinimumSize(oldButton.getMinimumSize());
              newButton.setMaximumSize(oldButton.getMaximumSize());
         private static int getIndex(Component c) {
              Container p = c.getParent();
              for (int i = 0; i < p.getComponentCount(); i++) {
                   if (p.getComponent(i) == c)
                        return i;
              return -1;
         public JButton getOKButton() {
              return okButton;
         public JButton getCancelButton() {
              return cancelButton;
         public JList getFileList() {
              return fileList;
         public JTextField getFilenameTextField() {
              return     filenameTextField;
         public JFileChooser getFileChooser() {
              return fileChooser;
         protected JButton[] getButtons(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JButton)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JButton[] arr = new JButton[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JButton) v.get(i);
              return arr;
         protected JTextField[] getTextFields(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JTextField)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JTextField[] arr = new JTextField[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JTextField) v.get(i);
              return arr;
         protected JList[] getLists(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JList)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JList[] arr = new JList[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JList) v.get(i);
              return arr;
         public File[] getSelectedFiles() {
              File[] f = fileChooser.getSelectedFiles();
              if (f.length == 0) {
                   File file = fileChooser.getSelectedFile();
                   if (file != null)
                        f = new File[] { file };
              return f;
         public void mousePressed(MouseEvent evt) {
              Object src = evt.getSource();
              if (src == fileList) {
                   if (evt.getModifiers() != InputEvent.BUTTON1_MASK) return;
                   int index = fileList.locationToIndex(evt.getPoint());
                   if (index < 0) return;
                   fileList.setSelectedIndex(index);
                   File[] arr = getSelectedFiles();
                   if (evt.getClickCount() == 2 && arr.length == 1 && arr[0].isFile())
                        actionPerformed(new ActionEvent(okButton, 0, okButton.getActionCommand()));
         public void mouseReleased(MouseEvent evt) {}
         public void mouseClicked(MouseEvent evt) {}
         public void mouseEntered(MouseEvent evt) {}
         public void mouseExited(MouseEvent evt) {}
         public void keyPressed(KeyEvent evt) {
              Object src = evt.getSource();
              int code = evt.getKeyCode();
              if (code == KeyEvent.VK_ESCAPE)
                   actionPerformed(new ActionEvent(cancelButton, 0, cancelButton.getActionCommand()));
              if (src == filenameTextField) {
                   if (code != KeyEvent.VK_ENTER) return;
                   fileList.getSelectionModel().clearSelection();
                   actionPerformed(new ActionEvent(okButton, 0, "enter"));
         public void keyReleased(KeyEvent evt) {}
         public void keyTyped(KeyEvent evt) {}
         public void actionPerformed(ActionEvent evt) {
              Object src = evt.getSource();
              if (src == cancelButton) {
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);
              else if (src == okButton) {
                   File[] selectedFiles = getSelectedFiles();
                   Object obj = fileList.getSelectedValue(); // is null when no file is selected in the JList
                   String text = filenameTextField.getText().trim();
                   if (text.length() > 0 && (obj == null || selectedFiles.length == 0)) {
                        File d = fileChooser.getCurrentDirectory();
                        Vector vec = new Vector();
                        StringTokenizer st = new StringTokenizer(text, "\"");
                        while (st.hasMoreTokens()) {
                             String s = st.nextToken().trim();
                             if (s.length() == 0) continue;
                             File a = new File(s);
                             if (a.isAbsolute())
                                  vec.add(a);
                             else
                                  vec.add(new File(d, s));
                        File[] arr = new File[vec.size()];
                        for (int i = 0; i < arr.length; i++)
                             arr[i] = (File) vec.get(i);
                        selectedFiles = arr;
                   if (selectedFiles.length == 0) {
                        Toolkit.getDefaultToolkit().beep();
                        return;
                   if (selectedFiles.length == 1) {
                        File f = selectedFiles[0];
                        if (f.exists() && f.isDirectory() && text.length() > 0 && evt.getActionCommand().equals("enter")) {
                             fileChooser.setCurrentDirectory(f);
                             filenameTextField.setText("");
                             filenameTextField.requestFocus();
                             return;
                   boolean filesOnly = (fileChooser.getFileSelectionMode() == JFileChooser.FILES_ONLY);
                   boolean dirsOnly = (fileChooser.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY);
                   if (filesOnly || dirsOnly) {
                        for (int i = 0; i < selectedFiles.length; i++) {
                             File f = selectedFiles;
                             if (filesOnly && f.isDirectory() || dirsOnly && f.isFile()) {
                                  Toolkit.getDefaultToolkit().beep();
                                  return;
                   fileChooser.setSelectedFiles(selectedFiles);
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);

  • File filter in JFileChooser

    How do I set multiple file filters when using JFileChooser?

    Put the ExampleFileFilter.class in your package then use this code:
    JFileChooser selez = new JFileChooser();
    ExampleFileFilter filtro = new ExampleFileFilter();
    filtro.addExtension("mp3");
    filtro.setDescription("File Mp3");
    selez.setAcceptAllFileFilterUsed(false);
    selez.setCurrentDirectory(new java.io.File("C:\\"));
    selez.setDialogTitle("Select your MP3");
    selez.setFileFilter(filtro);
    selez.setFileSelectionMode(javax.swing.JFileChooser.FILES_AND_DIRECTORIES);
    selez.setMultiSelectionEnabled(true);
    int retval = selez.showDialog(this, null);
    if (retval == JFileChooser.APPROVE_OPTION) {
    // Code if user select file and click OK

Maybe you are looking for

  • PDFMaker in Acrobat 9 Standard not working

    I'm running Windows 7 x64 and have Acrobat 9 (updated through 9.4).  In January, I downloaded a trial of Acrobat X, decided I didn't want it.  I uninstalled it and still have 9.  However (and I think this is when it began), the Create Adobe PDF funct

  • F-110 Automatic payment programme

    Hello, I have created several bank accounts for one bank house. In bank selection, when defining the ranking order, I can only indicate the house bank, I cannot enter any accounts. Does this mean I am only able to choose one specific account from all

  • Can't install free trial of creative cloud

    Trying to download free trial of CC Premiere Pro. Web site says its downloading but nothing happens

  • About  'PDF Open Parameters'  in Android environment.

    Hello; I'm writing an application for GalaxyTab. I need to show a specified page of the pdf file. So, I wrote the following code.     Intent intent = new Intent(Intent.ACTION_VIEW);     intent.setDataAndType(Uri.parse("file:///mnt/sdcard/download/myp

  • Change default language for the logon Page

    Hello, On a SAP Portal 7.0 SP 17 I've a problem with the language of the Logon Page: is always in English. If I go to internet explorer -> tools -> internet options -> languages I've set Franch as language. When I open the Logon Page (http://xxxx:501