FileDialog Filefilter

Hello people,
Am having a problem using a file filter to select a particular list of files without showing all other files, but I have searched the web, but did not get an example. i don't want to use JFileChooser, I have to use the FileDialog. Please guys help a brother.
I have encloded a sample here
import java.awt.*;
import java.awt.event.*;
/** A class to test filedialogs */
public class Filer extends Frame
public static void main(String[] adsd){
Filer f = new Filer();
    public Filer ()
        //setLayout (new GridLayout (5, 1));
        this.show();
       // setVisible(true);
        pack ();
        setSize(100,100);
        Button load;
        add (load = new Button ("Load..."));
        load.addActionListener (new ActionListener ()
            public void actionPerformed (ActionEvent e)
                FileDialog d = new FileDialog (Filer.this, "Load...", FileDialog.LOAD);
                d.pack ();
                d.show ();
                d.dispose ();
}

Thanks hiwa for your responce. I tried creating a class that implements the FilenameFilter, but it did not work. Please could you people look at my code and see where am making a mistake?
Thanks guys.
import java.io.*;
import java.awt.*;
import java.awt.event.*;                  /** A class to test filedialogs */
public class Filer extends Frame
    public static void main (String [] adsd)
        Filer f = new Filer ();
    public Filer ()
    { //setLayout (new GridLayout (5, 1));
        this.show ();
        setVisible (true);
        pack ();
        setSize (100, 100);
        Button load;
        add (load = new Button ("Load..."));
        load.addActionListener (new ActionListener ()
            public void actionPerformed (ActionEvent e)
                FileDialog d = new FileDialog (Filer.this, "Load...", FileDialog.LOAD);
                d.setFilenameFilter (new ImageNameFilter ());
                d.pack ();
                d.show ();
                d.dispose ();
    class ImageNameFilter implements FilenameFilter
    public boolean accept (File dir, String name)
        return (name.endsWith (".java") ||
                name.endsWith (".JAVA"));
}Thanks guys

Similar Messages

  • Problem in using FilenameFilter with FileDialog

    perhaps, i dont know how to use FilenameFilter with FileDialog because the following approach doesn' work
    FileDialog fd=new FileDialog(myframe,"Select an image");
    fd.setFilenameFilter(new filefilter());                                                                                                                           
                                                                                                             class filefilter implements FilenameFilter{
        public boolean accept(File dir, String name) {
            if(name.endsWith("jpg")||name.endsWith("gif")||name.endsWith("png")){
                          return true; 
                 return false;
    }if anyone have compatible idea then please let me know.
    thanks

    Did you print out the value of "dir" and "name" to make sure they contain what you expect?
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html

  • 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;
    }

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

  • How to pre-define the "save as type" using fileDialog or fileChooser?

    Hello everyone,
    I have a fileDialog. I now want to save a file by specified extensions i.e. docs,gif,etc. How can I do that? by default, the "save as type" box is "all files".
    thanks a lot
    SQ

    if you are using the java.awt.FileDialog,
    call its .setFilenameFilter() method, passing to it
    an instance of java.io.FilenameFilter, in which you override the
    .accept(File dir, String name) method
    to specify the file extensions you'd like. You'll have to do some pattern matching of the extended characters (*.___)...
    if you're using JFileChooser, do similar calling
    .setFileFilter(javax.swing.filechooser.FileFilter) setting an instance of FileFilter that overrides its
    .accept(File file) method.
    Hope that helps.

  • FileDialog, how to set filter?

    i try to use
    setFilenameFilter(FilenameFilter filter)
    to set filter for FileDialog, but FilenameFilter is an interface, what is the story?
    do u know how to set filter?
    thanks in advance

    Construct a FileFilter class like:
    public class CustomFilter implements FileFilter{
         public CustomFilter(){
    public String getFileExtension(File file) {
    String ext = null;
    String s = file.getName();
    int i = s.lastIndexOf(".") + 1;
    ext = s.substring(i).toLowerCase();
    return ext;
    public String doSomething(){
    //do Something
    //return something
    and use the setFileFilter(FileFilter filter) method.

  • FileDialog....filter help!

    I'm still utterly confused as to how a FilenameFilter works for a filedialog...can anyone give me any sample code? I tried the following:
    fileDialog.setFilenameFilter(new java.io.FilenameFilter() {
                public boolean accept(File pathname) {
                    if (pathname.getName().endsWith(".ars")) {
                        return true;
                    else {
                        return false;
            });and got this error:
    <anonymous windowResults$6> is not abstract and does not override abstract method accept(java.io.File,java.lang.String) in java.io.FilenameFilterwindowResults being the class this is all in.

    java.io.FilenameFilter accept method takes two parameters a File object and a String. Use it with a java.awt.FileDialog. A javax.swing.filechooser.FileFilter's accept method takes a single String parameter and is used with a javax.swing.JFileChooser.
    Hope that helps
    DB

  • Filedialog File type shows *.*, how can I change?

    I wanna change the file type showing in FileType in FileDialog, please help.

    This code is for JFileChoser. You should be able to adapt it for your requirement.
    JFileChooser chooser = new JFileChooser();
    chooser.addChoosableFileFilter(new FileExtensionFilter("Text files", new String[] {".txt"}));
    chooser.addChoosableFileFilter(new FileExtensionFilter("SQL files", new String[] {".sql"}));
    package net.sourceforge.squirrel_sql.fw.util;
    * Copyright (C) 2001 Colin Bell
    * [email protected]
    * This program is free software; you can redistribute it and/or
    * modify it under the terms of the GNU General Public License
    * as published by the Free Software Foundation; either version 2
    * of the License, or any later version.
    * This program is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    * GNU General Public License for more details.
    * You should have received a copy of the GNU General Public License
    * along with this program; if not, write to the Free Software
    * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    import java.io.File;
    public class FileExtensionFilter extends javax.swing.filechooser.FileFilter
                    implements java.io.FileFilter {
        private String _description;
        private String[] _exts;
        public FileExtensionFilter(String description, String[] exts) {
            super();
            _exts = exts;
            StringBuffer buf = new StringBuffer(description);
            buf.append(" (");
            for (int i = 0; i < _exts.length; ++i) {
                buf.append("*").append(_exts);
    if (i != (_exts.length - 1)) {
    buf.append(", ");
    buf.append(")");
    _description = buf.toString();
    public boolean accept(File file) {
    if (file.isDirectory()) {
    return true;
    String name = file.getName().toLowerCase();
    for (int i = 0; i < _exts.length; ++i) {
    if (name.endsWith(_exts[i])) {
    return true;
    return false;
    public String getDescription() {
    return _description;

  • How to create a FileDialog in the following...

    Hey there.
    I'm trying to create a FileDialog window using the parents frame to introduce a SAVE dialog that will
    allow the user to save to a file of their choosing. I'm not sure how to use it.
    If anyone could take the time to explain to me what I'm using and where it goes I'd greatly appreciate it.
    Thanks.
    The following saves the current state of the picture as a text file.
        public void saveImage(Image pic, Frame parent)
            String rgbHex;
            PrintWriter outFile;
            String fileName = "save.txt"
          try  
                outFile = new PrintWriter(new FileWriter(fileName));
                outFile.println("Width " + pic.getWidth() + " Height " + pic.getHeight());
                for (int y=0; y<pic.getHeight(); y++)                
                   for (int x=0; x<pic.getWidth(); x++)            
                      rgbHex = pic.getPixel(x, y);
                      outFile.print(rgbHex + " ");
                   outFile.println();
                outFile.close();
            catch (IOException e){ 
               System.err.println("Error writing file "+ fileName + ": " + e.toString());
    }Edited by: latitudeD6 on Apr 23, 2008 7:06 PM

    Check out the following link for sample code:
    [http://forum.java.sun.com/thread.jspa?forumID=513&threadID=157831|http://forum.java.sun.com/thread.jspa?forumID=513&threadID=157831]

  • Opening a file with custom FileDialog. (VERY URGENT)

    hi everybody,
    I have a problem and stuck. I have developed a MDI application that provides all function like open saved files, create new, edit and lots of other. It only opens, save ,edit etc the graphical diagrams inside JInternalFrames. I have an icon on my desktop when clicked opens this Application. Just like Editplus, Word or some other application when you click on the icon it opens that. Same way I have created such functionality.
    Now instead of this I have created a custom FileDialogfrom which the user selects this application and is opened. Now I have small icon for this FileDialog on the desktop when opened gives the interface to select the files to be opened. My FileDialog just looks like the FileDialog but some more functionality and more components like JComboBox, Jlist, JtextField, JButtons etc. in it and have removed some of them. I am extending JDialog. But now my probelm is when you select a file and click open, it should open the selected file. How can I achive this functionality in my custom FileDialog as I am not extending FileDialog and as it is built in the FileDialog. How can I open the files with any extension in it's related application e.g .doc files to be opened in MicrosoftWord, .txt to be opened in notepad, .c or .cpp in Visual Studio C++ etc.
    How can I put this kind of functionality in my custom FileDialog. It's really important for me please any comments will help me alot. Thanks for the help

    Hello,
    I think you can write :
    Runtime.getRuntime().exec("start.exe " + MyFileDialog.getDirectory() + MyFileDialog.getFile());
    So, "start.exe" choose the application (not valid for NT machine), ".getDirectory()" return the PATH and ".getFile()" return the NAME.
    Best regards from France
    Thierry

  • JFileChooser/FileDialog TextField selections

    I have a program which will use file extension for file type associations.
    What I want is when a user views the Dialog to save a file, this file extension to be in the FileDialog/JFileChooser, but unselected. An example of this would be when the user selects 'save as', a FileDialog appears with a default name:
    filename.extension
    where 'filename' is selected/highlighted and '.extension' is not.
    This seems technically easy to do, but I can't find any documentation on how to do it. I know I can just add on an extension after the user sets the name and closes the dialog, but I'd rather not go that route.
    Thanks in advance
    Edited by: sierratech on Oct 17, 2008 12:29 AM

    this seems to work OK
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class Testing
      JTextField tf;
      public void buildGUI()
        JFrame f = new JFrame();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFileChooser  fc = new JFileChooser(".");
        fc.setSelectedFile(new File("test.txt"));
        getChooserTextField(fc.getComponents());
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            tf.select(0,tf.getText().indexOf("."));
        fc.showSaveDialog(f);
        f.setVisible(true);
      public void getChooserTextField(Component[] comp)
        for(int x = 0; x < comp.length; x++)
          if(comp[x] instanceof JPanel) getChooserTextField(((JPanel)comp[x]).getComponents());
          else if(comp[x] instanceof JTextField)
            tf = ((JTextField)comp[x]);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • How to display FileDialog in applet?

    Hi all,
    I looked FileDialog constructors but only Frame can be the owner of the dialog? Is there a way to do display it in applet?
    Thank you.

    Try:
    JOptionPane.getFrameForComponent(this);
    Remember:
    Applets need to be signed to access the file system.

  • From JavasSript called signed (FileDialog) Applet Problems...

    Hallo,
    I want to read a by JavaScript opened selected file with the FileDialog in a Byte[], and give this Byte[] back to JavaScript. I have this code for my unsigned applet working fine without reading the selected file in a byte[], but give the filepath and name back to JavaScript:
    import java.applet.Applet;
    import java.awt.FileDialog;
    import java.awt.Frame;
    import netscape.javascript.JSObject;
    public class OpenFileDialogJava6 extends Applet
         private static final long serialVersionUID = -1401553529888391702L;
         private Frame m_parent;
        private FileDialog m_fileDialog;
    *Displays a file dialog, calling standard JavaScript methods when the*
    user selects a file or cancels the dialog.
    *    public void newFileDialog(String onFileJS, String onCancelJS)*
    *          System.out.println("open Dialog...");*
    *         openDialog(onFileJS, onCancelJS);*
    *Displays a file dialog, calling the specified JavaScript functions when*
    the user selects a file or cancels the dialog.
    @param onFile The name of the function to call when the user selects a
    *file.*
    @param onCancel The name of the function to call when the user cancels
    *a dialog selection.*
        public void openDialog(final String onFile, final String onCancel)
             System.out.println("Calling open dialog...");
             if (m_parent == null)
                 m_parent = new Frame();
            if (m_fileDialog == null)
                 m_fileDialog = new FileDialog(m_parent, "Medien hinzuf&uuml;gen", FileDialog.LOAD);             
            m_fileDialog.setVisible(true);       
            m_fileDialog.toFront();
            final String directory = m_fileDialog.getDirectory();  
            final String returnFile = m_fileDialog.getFile();
             m_fileDialog.setVisible(false);     
            m_parent.setVisible(false);
            if (returnFile == null)
                 System.out.println("onCancel");
                 callJavaScript(onCancel);     
            else
                 System.out.println("onFile");
                 System.out.println(directory+returnFile);
                 callJavaScript(onFile, directory+returnFile);
         private void callJavaScript(final String func, final Object... args)
              final JSObject window = JSObject.getWindow(OpenFileDialogJava6.this);
              if (window == null)
                  System.out.println("Could not get window from JSObject!!!");
                  return;
              System.out.println("Calling func through window");
              try
                   window.call(func, args);
              catch (final Exception e)
                  System.out.println("Got error!!"+e.getMessage());
                  e.printStackTrace();
                  showError(e);
              System.out.println("Finished JavaScript call...");
         private void showError(final Exception e)
              final String[] args = new String[]{e.getMessage()};
              final JSObject window = JSObject.getWindow(this);
              try
                   window.call("alert", args);
              catch (final Exception ex)
                   System.out.println("Error showing error! "+ex);
    }I self-sign the Jar and write that byte[] test = (byte[]) java.security.AccessController.doPrivileged(
              new java.security.PrivilegedAction() to the code in where I want to read the file.....
    So now I started to change the code in the public void openDialog(final String onFile, final String onCancel) to get the Byte[] of the selected File
            final String directory = m_fileDialog.getDirectory();  
            final String returnFile = m_fileDialog.getFile();
            final File file = new File(directory+
                    File.separator +returnFile);
            byte[] test = (byte[]) java.security.AccessController.doPrivileged(
              new java.security.PrivilegedAction()
                   public Object run()
                      try
                          FileInputStream fileInputStream = new FileInputStream(file);
                          byte[] data = new byte[(int) file.length()];
                          try
                               fileInputStream.read(data);
                               fileInputStream.close();
                               return data;
                          catch(IOException iox)
                                System.out.println("File read error...");
                                iox.printStackTrace();
                                return null;
                     catch (FileNotFoundException fnf)
                           System.out.println("File not found...");
                           fnf.printStackTrace();
                           return null;
             m_fileDialog.setVisible(false);     
            m_parent.setVisible(false);
    .......Without signing the jar: I get this in IE 8:
    Meldung: java.security.AccessControlException: access denied ("java.io.FilePermission" "C:\xampp\htdocs\index.php" "read")
    Zeile: 6
    Zeichen: 1
    Code: 0
    URI: file:///E:/FH%20Kempten/Semester%206/Java/Java%20Projekte/OpenFileDialogJava6/bin/Neues%20Textdokument.html
    Ok this I understand, but when I sign it, I open my FileDialog, select a file, ok -> nothing happens: Firfox and IE show me:
    uncaught exception: java.lang.reflect.InvocationTargetException*
    And in Java Console nothing: Just my Output:
    open Dialog...
    Calling open dialog...

    Hallo,
    I want to read a by JavaScript opened selected file with the FileDialog in a Byte[], and give this Byte[] back to JavaScript. I have this code for my unsigned applet working fine without reading the selected file in a byte[], but give the filepath and name back to JavaScript:
    import java.applet.Applet;
    import java.awt.FileDialog;
    import java.awt.Frame;
    import netscape.javascript.JSObject;
    public class OpenFileDialogJava6 extends Applet
         private static final long serialVersionUID = -1401553529888391702L;
         private Frame m_parent;
        private FileDialog m_fileDialog;
    *Displays a file dialog, calling standard JavaScript methods when the*
    user selects a file or cancels the dialog.
    *    public void newFileDialog(String onFileJS, String onCancelJS)*
    *          System.out.println("open Dialog...");*
    *         openDialog(onFileJS, onCancelJS);*
    *Displays a file dialog, calling the specified JavaScript functions when*
    the user selects a file or cancels the dialog.
    @param onFile The name of the function to call when the user selects a
    *file.*
    @param onCancel The name of the function to call when the user cancels
    *a dialog selection.*
        public void openDialog(final String onFile, final String onCancel)
             System.out.println("Calling open dialog...");
             if (m_parent == null)
                 m_parent = new Frame();
            if (m_fileDialog == null)
                 m_fileDialog = new FileDialog(m_parent, "Medien hinzuf&uuml;gen", FileDialog.LOAD);             
            m_fileDialog.setVisible(true);       
            m_fileDialog.toFront();
            final String directory = m_fileDialog.getDirectory();  
            final String returnFile = m_fileDialog.getFile();
             m_fileDialog.setVisible(false);     
            m_parent.setVisible(false);
            if (returnFile == null)
                 System.out.println("onCancel");
                 callJavaScript(onCancel);     
            else
                 System.out.println("onFile");
                 System.out.println(directory+returnFile);
                 callJavaScript(onFile, directory+returnFile);
         private void callJavaScript(final String func, final Object... args)
              final JSObject window = JSObject.getWindow(OpenFileDialogJava6.this);
              if (window == null)
                  System.out.println("Could not get window from JSObject!!!");
                  return;
              System.out.println("Calling func through window");
              try
                   window.call(func, args);
              catch (final Exception e)
                  System.out.println("Got error!!"+e.getMessage());
                  e.printStackTrace();
                  showError(e);
              System.out.println("Finished JavaScript call...");
         private void showError(final Exception e)
              final String[] args = new String[]{e.getMessage()};
              final JSObject window = JSObject.getWindow(this);
              try
                   window.call("alert", args);
              catch (final Exception ex)
                   System.out.println("Error showing error! "+ex);
    }I self-sign the Jar and write that byte[] test = (byte[]) java.security.AccessController.doPrivileged(
              new java.security.PrivilegedAction() to the code in where I want to read the file.....
    So now I started to change the code in the public void openDialog(final String onFile, final String onCancel) to get the Byte[] of the selected File
            final String directory = m_fileDialog.getDirectory();  
            final String returnFile = m_fileDialog.getFile();
            final File file = new File(directory+
                    File.separator +returnFile);
            byte[] test = (byte[]) java.security.AccessController.doPrivileged(
              new java.security.PrivilegedAction()
                   public Object run()
                      try
                          FileInputStream fileInputStream = new FileInputStream(file);
                          byte[] data = new byte[(int) file.length()];
                          try
                               fileInputStream.read(data);
                               fileInputStream.close();
                               return data;
                          catch(IOException iox)
                                System.out.println("File read error...");
                                iox.printStackTrace();
                                return null;
                     catch (FileNotFoundException fnf)
                           System.out.println("File not found...");
                           fnf.printStackTrace();
                           return null;
             m_fileDialog.setVisible(false);     
            m_parent.setVisible(false);
    .......Without signing the jar: I get this in IE 8:
    Meldung: java.security.AccessControlException: access denied ("java.io.FilePermission" "C:\xampp\htdocs\index.php" "read")
    Zeile: 6
    Zeichen: 1
    Code: 0
    URI: file:///E:/FH%20Kempten/Semester%206/Java/Java%20Projekte/OpenFileDialogJava6/bin/Neues%20Textdokument.html
    Ok this I understand, but when I sign it, I open my FileDialog, select a file, ok -> nothing happens: Firfox and IE show me:
    uncaught exception: java.lang.reflect.InvocationTargetException*
    And in Java Console nothing: Just my Output:
    open Dialog...
    Calling open dialog...

  • Javax.swing.filechooser.FileFilter

    Does anybody know why javax.swing.filechooser.FileFilter is an abstract class
    instead of an interface extending java.io.FileFilter ?
    Gordan

    Yeh - and while we are on the subject, why doesnt it implement java.io.FileFilter so you can use the same filter for the filechooser as you do for listing files? </bangheadagainstwall>

  • Java.io.file.list(FileFilter) problem

    When I add the following filter within the parentheses of the .list() method, I get a "cannot resolve symbol" error. It seems odd to me that all of a sudden the classpath needs to be different because I add this (unless I am mistaken as to the solution.
    BTW, I am using Sun ONE Studio 4 update 1. I can't figure out how to change the classpath for the project within the GUI anyway.
    Thanks,
    LNMEgo
            String [] files = filePath.list(
      new FileFilter()
         public boolean  accept(File file)
            if (file.isDirectory()) return false; // ignore if this is a directory
            String fileName = file.getName();//.toUpperCase; // get the name of the file in upper case
            if (fileName.endsWith(".TXT")) return true; // if it ends with .TXT, then accept it
            return false; // otherwise, ignore it
            );

    Hehe, you've danced around the solution/problem
    Check out the methods defined in the API
    String[] list()
    String[] list(FilenameFilter filter)
    File[] listFiles()
    File[] listFiles(FileFilter filter)
    File[] listFiles(FilenameFilter filter)
    You're trying to use a FileFilter, and return a String[].... look more closely.
    Either use a FilenameFilter and get your String[], or continue with the FileFilter, and receive a File[].
    Good luck,
    Radish21

Maybe you are looking for