FileDialog

How do use the FileDialog class to open a FileDialog box in your Java Program or is there something better to use?

Please look at javax.swing.JFileChooser
This will allow you to select (one or more ) Files or Directories while applying any filter you choose.
-John
null

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

  • Displaying only folders in FileDialog

    I would like to create a dialog box that would allow the user to
    choose a directory, not a file. Is there any way to use the FileDialog box available in AWT to do this (and using Swing is not an option and i know how to do it in JFileChooser)??
    Any ideas or samples to how to do this would be greatly appreciated!

    I have not tested if this works, but you can try using the directory filter below via FileDialog's setFilenameFilter method.
    public class DirectoryFilter implements java.io.FilenameFilter {
    public void accept(File dir, String name) {
    File file = new File(dir, name);
    return file.isDirectory();

  • Urgent - FileDialog behaviour in Mac OS

    Hi
    I have a Java Swing application which should allow the user to save data in a file using the FileDialog functionality. I find that on Windows, the application works properly i.e. it opens up a FileChooser window and one can enter the name of a file in which data is to be saved.
    However on MAC, I am unable to do so. Unless the file already exists, I am not able to save data from the application into a file.
    I would really appreciate a work around to this problem on a Mac.
    It is part of a project which I have to present today evening. I really appreciate some guidance about this.
    Thanks

    JFileChooser has a save and an open dialog.
    Maybe you did not explicitly use save.

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

  • FileDialog in SAVE mode does not throw file access error

    Hi,
    We are using FileDialog to SAVE and LOAD files.
    If a file is selected to which the user has no access, then LOAD dialog throws an
    error, but SAVE dialog does not.
    Have I skipped something ??
    Below is a sample code :
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestClass extends JFrame {
    public TestClass() {
    setSize(400, 400);
    JPanel l_objPanel = new JPanel();
    getContentPane().add(l_objPanel);
    final JButton l_objButton = new JButton("FileOpen");
    l_objPanel.add(l_objButton);
    l_objButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent p_objEvent) {
    FileDialog l_objDlg = new FileDialog(TestClass.this, "Save now", FileDialog.SAVE);
    l_objDlg.show();
    public static void main( String[] strArgs ) {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
    e.printStackTrace();
    TestClass l_objDlg = new TestClass();
    l_objDlg.show();

    The bug you pointed out is pretty different: JWS should work offline if no network connection is available, but no such behaviour is provided, never the less granted, if your server is down. No matter what your 'web-distributed' app is (ASP, SaaS, SOA, RIA, cloud, ...), you may have it work without a network, but no architectural pattern would ever remotely consider it should run if the providing server is down (and is not redirecting or, at least, sending some 'manageble' error).

  • Adding buttons to the FileDialog object

    Hello,
    I'd like to know if it's possible to add buttons to a FileDialog object in a java applet. The parent of the FileDialog is a Frame, so if I can add buttons to the Frame and show them with the File Dialog, that'll work just as good too.
    Thanks.

    You can submit feedback to Apple:
    http://www.apple.com/feedback/iphone.html

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

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

    Hi
    I'm using dialog boxes for Open and Save in my progra. Question is: Is it possible just to filter for java and text files.. heres my code.
    fd2=new FileDialog(this,"Save As..",FileDialog.SAVE);
    fd1=new FileDialog(this,"Open..",FileDialog.LOAD);
    Open.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent ae2 )
    txtmsg="";
    fd1.setVisible(true);
    String filename=fd1.getFile();
    String dirname=fd1.getDirectory();
    File openfile=new File(dirname,filename);
    try
    FileInputStream fis=new FileInputStream(openfile);
    int bytelength=fis.available();//calculates the file size
    for (int bytecount=0;bytecount<bytelength;bytecount++)
    char fch=(char)fis.read();
    txtmsg=txtmsg+fch;
    ta.setText(txtmsg);
    catch(Exception ioe)
    System.out.println("An exception has occured");
    );

    yes it is possible
    doublle click JAVA_HOME\demo\jc\swingset2\swingset2.jar (its long to start, be patient)
    for source code look in JAVA_HOME\demo\jc\swingset2\src\*.java
    marvinrouge

Maybe you are looking for

  • Exchange account not showing up in 10.9.2 Mail

    Just installed MacOS 10.9.2 and now I can't get my Exchange account to show up in Mail. Under System Preferences/Internet Accounts, I see the account and Mail, Contacts and Calendars are checked.  But if I start Mail and go to Preferences.../Accounts

  • HT1923 itunesHelper was not installed correctly. please reinstall itunes. error 7

    I am trying to install new version of itunes. It kept telling me that it was not installed properly. My os system is window 7. I unstalled apple related software through control panel and reinstalled new one. But still erros. Please help!!

  • Value mapping values to be reflected dynamically

    Hi All,    I have a scenario where R3 entries should be reflected in value mapping dynamically for a particluar field . Can anyone explain wht does the component SAP BASIS 7.00(NS- http://sap.com/xi/XI/System,MI -ValueMappingReplication) has the role

  • Clients uanble to connect to DHCP server when renewing.

    For the past week now, I get 2 or 3 windows 7 clients suddenly not able to get to the network when they first boot up, or when just logging back on. pc after coming back from lunch. my script doesn't run for drive mappings either.  the IP address loo

  • Editing Sound Files for CD Burning

    Is there a feature in iTunes that allows a user to custom edit ripped tracks and those purchased at iTunes Music Store? I like to make my own custom CD's, and just burning tracks straight from iTunes doesn't cut it. I can edit them to play back on iT