JFileChooser or FileDialog??? Dilema!!

hi there, I tried implementin a "Save As" Option using JFileChooser.. It works fine.. But wen i dont specify an extension.. it does not take the default extension specified using filters.
Ex.. Say i try to Save "test" and the file type below reads ".xml"..It wont append the extension name.
I can do a save as using FileDialog.. But it is not letting me filter the extensions.. I read tat filtering cannot be done on a windows platform.. but works on linux..
So.. wha say??

When i do a "Save As" without specifying the file
type.. will it not take the extension from the "Save
As" drop down box??Why would it? Appending a file extension automatically is a function of application logic that is beyond the scope of a generic component like JFileChooser. I suppose that it's possible that the equivalent file chooser component in Windows may have an option to do this for you, but that doesn't mean Java has to do the same thing.
How...?You get the selected extension filter, if you can. You can, cuz even if JFileChooser can't tell you, you can find the combobox that it uses in the component to display that choice and get the selected value. Then you just modify the File object that you get from the chooser to a new File with the extension.
This might be a nice function to include in a subclass of JFileChooser.

Similar Messages

  • JFileChooser or FileDialog

    hello,
    I want to drag a file from either JFileChooser or FileDialog to a canvas what is the code for dragsource ?

    When i do a "Save As" without specifying the file
    type.. will it not take the extension from the "Save
    As" drop down box??Why would it? Appending a file extension automatically is a function of application logic that is beyond the scope of a generic component like JFileChooser. I suppose that it's possible that the equivalent file chooser component in Windows may have an option to do this for you, but that doesn't mean Java has to do the same thing.
    How...?You get the selected extension filter, if you can. You can, cuz even if JFileChooser can't tell you, you can find the combobox that it uses in the component to display that choice and get the selected value. Then you just modify the File object that you get from the chooser to a new File with the extension.
    This might be a nice function to include in a subclass of JFileChooser.

  • JFileChooser vs FileDialog

    I've noticed that the JFileChooser opens very slowing and was wondering if it would be better to use the FileDialog. My application is a Swing app and I've heard on numerous occasions you should not mix AWT and Swing components in an application. Can someone tell me the best approach to create a correct my problem. THe JFileChooser is just too slow. Also, can someone tell me the reason for not mixing Swing and AWT components?
    thanks

    hello,
    using a FileDialog shouldnt be a problem in a swing application. i agree with you that JFileChooser is abit slow but look on the positive side of the JFileChooser, you can customize it to your liking, and even can set the fileChooser to show a prieview of some files, i mean its fully customizable compared to a FileDialog. if your application is a simple then you rather use a FileDialog but if its major where the GUI makes a difference than use JFileChooser. well this is just a suggestion
    asrar

  • JFileChooser or FileDialog.... so many questions

    hi all,
    i have searched the forum to no avail so i need your help.
    i am wanting to use jfilechooser to get the directory listing and files over a tcp/ip connection. i send the getdirectory message to the server and it returns the directory. next, i send the getfiles message to the server and it returns the files in the directory. i can get the directory by overriding the setcurrentdirectory()method but how do i set the files in the filechooser. can it even be done this way. if so, what methods do i need to override to accomplish this task. any help will be greatly appreciated
    thanks

    I believe JFileChooser is only for file systems that the current JVM has access to (in other words, not remote file systems).

  • JFileChooser: filename changes when i change directories

    Hi,
    I'm having a problem with a file chooser : when changing directories (change from default directory to dir of my choice), the "Filename:" text gets changed too.
    Here is what is actually happening :
    - I use setSelectedFile(<default file>) on my file chooser before opening
    - it opens with <default file> in the Filename field.
    - I switch to a different directory by double clicking within the area which shows the directories and files.
    -->> problem : my filename takes the name of the directory which i double clicked.
    ** surprisingly enough , when i select a directory from the drop down list of the filechooser the above problem doesnt happen .
    Below is my code. cud someone tell what is missing/wrong. plz treat this as urgent , i got to ship the code after 4 hrs
    Thanks in advance for any help, i will more than glad to offer duke dollars for this one.
    KG
    public class StepSaveFileDialog extends JFileChooser  {
        String fileExtension = null;
        JFileChooser fileDialog = null;
        String reportName = null;
          public StepSaveFileDialog(String fileExtension,String reportName) {//used to get the fileextension and the reportName
            this.fileExtension = fileExtension;
            this.reportName = reportName.replaceAll(" ","_"); 
          public String getSaveDialog() throws IOException {
            String filePath = null;
            fileDialog = new JFileChooser();
            fileDialog.setDialogType(JFileChooser.SAVE_DIALOG);
            fileDialog.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fileDialog.setAcceptAllFileFilterUsed(true);
            fileDialog.setFileFilter(new StepFileFilter(this.fileExtension));
            String dfltFilePath = ReportEngine.getDefaultReportSavePath();
            File selFile = null;
            String date = new StepDate(System.currentTimeMillis()).toString();
            date = date.replaceAll("/","");
            reportName = reportName + "_" + date;
            if (dfltFilePath != null) {
                selFile = new File((new File(dfltFilePath)).getCanonicalPath() + "\\" + reportName);
            }else{
                selFile = new File(reportName);
            fileDialog.setCurrentDirectory(selFile);
            fileDialog.setSelectedFile(selFile);
            int option = fileDialog.showSaveDialog(StepMainFrame.getInstance());
            if (option == JFileChooser.APPROVE_OPTION) {
                selFile = fileDialog.getSelectedFile();
                    File reportFile = new File(selFile.toString());
                    boolean success = reportFile.createNewFile();
                    if (!success) {
                        fileDialog.show();
                        fileDialog.setVisible(true);
                        int overwriteOption = JOptionPane.showConfirmDialog(
                                fileDialog, selFile.getAbsolutePath()
                                        + StepStatusMessage.PROMPT_FOR_OVERWRITE);
                        if (overwriteOption == JOptionPane.NO_OPTION) {
                            filePath = getSaveDialog();
                            return filePath;
                    filePath = reportFile.getAbsolutePath();
            return filePath;
    the ReportEngine.getDefaultReportSavePath() is like this
    private String getDefaultReportSavePath() {
            Properties prop = new Properties();
            String dfltFilePath = null;
            try {
                File file = new File(CONFIG_FILE);
                FileInputStream inputStream = new FileInputStream(file);
                prop.load(inputStream);
                inputStream.close();
                dfltFilePath = (String) prop.get("step.reportFilePath");
            } catch (IOException ioe) {
                StepStatusBar.getInstance().writeErrorMessage(ioe.getMessage());
                StepLogger.getLogger().fatal(ioe.getMessage(), ioe);
            return dfltFilePath;
    }the fileFilter is like this :
    public class StepFileFilter extends javax.swing.filechooser.FileFilter {
        String fileExtension = null;
        public StepFileFilter(String fileExtension) {
            this.fileExtension = fileExtension;
        public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(this.fileExtension);
        public String getDescription() {
            return this.fileExtension;
    }

    You will still be able to navigate through the area
    where the files and directories are displayed with
    FILES_ONLY. Clicking on a file will cause its name to
    appear in the File Name field, while double-clicking
    on a directory will navigate into it.
    FILES_AND_DIRECTORIES causes the names of both files
    and directories to appear in the File Name field when
    they are clicked.
    MikeHey Mike , thanks a lot .... it worked

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

  • Why my JFileChooser showed as a FileDialog?

    Hello!
    I'm doing a project to update some existing codes. I made a change to use JFileChooser to replace FileDialog since I can customize JFileChooser. However, after I have replaced FileDialog with JFileChooser in code, it still show as FileDialog when I run it. I'm very sure that I'm using the changed codes since I can see other changes I made in the file. The runtime environment could be a little strange, I heard it may not support Java.Swing. However, I used some other Swing components they all come out fine. It seems that JFileChooser is not supported so it fails back to FileDialog automatically, does anyone know anything about this?
    Thank you very much.
    Edited by: cutty on Jun 5, 2008 9:50 AM

    We can't really diagnose your problem just with what you posted.
    cutty wrote:
    The runtime environment could be a little strange, I heard it may not support Java.Swing.What environment? Platform, OS version, JVM version.
    It seems that JFileChooser is not supported so it fails back to FileDialog automatically, does anyone know anything about this?Write a small test program that simply creates a JFileChooser and displays it, and does nothing else. If it displays a JFileChooser, you'll know there's a bug in your code. If it displays a native file chooser like AWT does, then you may be correct.

  • FileDialog, not JFileChooser, how to set filter? help+help!

    i want to add file filter to the bottom combo box control of FileDialog, but i have no idea.
    1. setFile("*.txt;*.java;") works in a silly style
    2. FilenameFilter doesn't work (return true or false makes no diff from accept function.
    if you used FileDialog before or saw some examples which work well, please give me a hand.
    please don't guess if u never use before.
    many thanks

    setFileNameFilter do not work for Windows 95, 98, or NT 4.0. So better use JFileChooser

  • 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();

  • How to make a JFileChooser response to my keyevent?

    I wanna delete a file from JFileChooser as I press "Delete" key.The file is removed both from disk and from JFileChooser.How to accomplish this purpose? Thanks.

    Sorry, JFileChooser doesn't support deleting files (yet).
    Sometimes it actually makes sense to use java.awt.FileDialog
    instead of JFileChooser, even in a program that otherwise is
    pure Swing.
    I also recommend posting questions like this in the Swing
    forum instead. There are a lot more experts paying attention
    there.
    Cheers,
    Leif Samuelsson
    Java Swing Team
    Sun Microsystems, Inc.

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

  • Show files information with JFileChooser

    Does anyone know how to use JFileChooser to show files information such as size, type and last modified when mouse moves over the files ?
    This function seems to work well with FileDialog class under XP but does not work with JFileChooser.
    Jay

    Revealing hidden files and getting that error are 2 completely different thing. Even though you can't see hidden files in a finder window doesn't mean they are inaccessible to programs and the OS. They are just hidden from view to the user.

  • JFileChooser incredibly slow both to initialize and to change directories

    I have searched the forums for this and haven't found anything useful. I have the following code running in jre1.6.0_07:
    JFileChooser objFileChooser = new JFileChooser();
    objFileChooser.setAcceptAllFileFilterUsed(true);
    objFileChooser.addChoosableFileFilter(new CookbookFileFilter());
    objFileChooser.setMultiSelectionEnabled(false);
    if(objFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
         getModel().load(objFileChooser.getSelectedFile().getAbsolutePath());the first line takes upwards of 20-30 seconds or more to get past when debugging - I don't know how long it takes when running without the debugger however the application does sit for a while after pressing the hotkey to activate the actionlistener. That's a problem, but if that was the only thing, I would do as another post suggested and initialize the jFileChooser from a separate thread during the initialization of the window or application...however, I also run into an issue whenever I change directories where it takes a subset of the initialization time(maybe 10-15 seconds instead of 20-30) to change the directory. This happens in both System and Cross-Platform Look and Feel-s.
    I've looked into the issue with zip files and there are no (0) zip files(or archives of any kind) in the initial directory(My Documents folder). There is a small delay going to My Computer through Windows normally but it may be 1-2 seconds at most, and only sometimes. Notepad opens the Load / Save Dialogs within milliseconds and while I do understand Java is not Notepad, I'm willing to accept a few seconds (like maybe 5 or so), but not 20-30. I also looked into potentially using JDK 7 however I can't seem to get Eclipse to work with it and it consistently uses the JDK 6.
    If a solution can not be found to this, then is there a way to hook into the dialog/control in order to change the mouse cursor to the 'wait' cursor and change it back when the directory is ready? I'd like to provide some communication to the user. Thanks!

    camickr,
    I did include a "Short, Self Contained, Compilable and Executable Example Program (SSCCE)" in my initial posting; and I also included Code Formatting as everyone can see. I've been a programmer for over 10 years, closer to 15 and have almost 8 years experience with Java so I'm not about to ask a question without investigating the solution on my own first(to avoid wasting people's time. Admittedly all I posted was the snippet but that entire snippet could be put within Main like this below and it would be exactly the same without the waste of space. The machine I have running / developing this on is: Athlon 64 3000, 1 GB RAM, about 13 or 14 total hard drive partitions and removable media drives, running under Windows XP SP2. I can even eliminate the Choosable Filter in the example as I do below and the JFileChooser takes (31 seconds on average over 5 iterations, I timed it after I originally posted this) to fully display the dialog and all files and deliver control back to the user. That is unacceptable and one can not deny that it's the class itself when FileDialog runs significantly faster and programs outside of Java executing the standard XP File Dialog run even faster still. If this code is not good enough, I don't know how much shorter or self contained I can make this code example without removing the configuration lines between the initialization and that would defeat my cause as I need the Look and feel customization and prefer not writing my own File Chooser Dialog. Here's the code w/ the main function and all.
    import javax.swing.JFileChooser;
    public class Example
         public static void main(String[] args)
              JFileChooser objFileChooser = new JFileChooser();
              objFileChooser.setAcceptAllFileFilterUsed(true);
              objFileChooser.setMultiSelectionEnabled(false);
              if(objFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
                   System.out.println("Approved");
    }Thanks,
    Seth

  • NullException when setUI on JFileChooser

    I wrote a sub class of MetalFileChooserUI, and set it for my file chooser. but when i show the file chooser dialog, the icons for the files is disappeared. if i click the file list item, NullException occur. why?
    MY code:
    public class MyChooser extends JFileChooser {
    public MyChooser(String file) {
    super(file);
    setUI(new MyChooserUI());
    public class MyChooserUI extends MetalFileChooserUI {
    public MyChooserUI(JFileChooser fc) {
    super(fc);
    Error Message:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.metal.MetalFileChooserUI$FileRenderer.getListCellRendererComponent(MetalFileChooserUI.java:536)
         at javax.swing.plaf.basic.BasicListUI.paintCell(BasicListUI.java:87)
         at com.incors.plaf.kunststoff.KunststoffListUI.paintCell(KunststoffListUI.java:91)
         at javax.swing.plaf.basic.BasicListUI.paint(BasicListUI.java:149)
         at com.incors.plaf.kunststoff.KunststoffListUI.update(KunststoffListUI.java:72)
         at javax.swing.JComponent.paintComponent(JComponent.java:395)
         at javax.swing.JComponent.paint(JComponent.java:687)
         at javax.swing.JComponent.paintChildren(JComponent.java:498)
         at javax.swing.JComponent.paint(JComponent.java:696)
         at javax.swing.JViewport.paint(JViewport.java:668)
         at javax.swing.JComponent.paintWithBuffer(JComponent.java:3878)
         at javax.swing.JComponent._paintImmediately(JComponent.java:3821)
         at javax.swing.JComponent.paintImmediately(JComponent.java:3672)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.Dialog.show(Dialog.java:380)
         at javax.swing.JFileChooser.showDialog(JFileChooser.java:614)
         at javax.swing.JFileChooser.showOpenDialog(JFileChooser.java:517)

    I think JFileChooser is a platform independent solution and Network Neighbourhood is a Windows implementation.
    You can use use a FileDialog, I think it uses the Window native open dialog.
    Use code something like this:
    File Dialog fileDialog = new FileDialog( parent frame );
    fileDialog.setMode(FileDialog.LOAD);
    fileDialog.show();
    if (fileDialog.getFile() == null)
    return;
    File file = new File( fileDialog.getDirectory(), fileDialog.getFile() );

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

Maybe you are looking for