Re: JFileChooser and existing files

From: Allan Bruce (allanmb_at_TAKEAWAYf2s.com)
Date: 01/12/04


Date: Mon, 12 Jan 2004 18:38:17 -0000


"Andrew Thompson" <andrew64@bigNOSPAMpond.com> wrote in message
news:CLAMb.8247$Wa.5455@news-server.bigpond.net.au...
> "Allan Bruce" <allanmb@TAKEAWAYf2s.com> wrote in message
> news:btu1ve$b1r$1@news.freedom2surf.net...
> | I am using a JFileChooser to select a file which I wish to save
> a String to.
> | This works fine however if the file already exists, my program
> just writes
> | over the file without any warning. Is there an option for the
> JFileChooser
> | to ask if the user wishes to replace the existing file, just
> like a Windows
> | FileChooser?
>
> I am pretty sure the Windows file chooser
> does _not_ do any such checking. It is
> really up to the programmer to check..
>
> if file.exists()
> {
> if ( JOptionPane.showConfirmDialog("Are you
> sure?")==JOptionPane.YES_OPTION )
> (..... write the file)
> }
>

I created my own class that extends the JFileChooser and over-rides the
approveSelection(). This makes it feel much more like the Windows
FileChooser, as it provides the dialog within the FileChooser itself. (By
the Windows FileChooser, I mean the Win32 one which I have used extensively
from C/C++).
I am new to Java, if my code below has a problem, could you please let me
know?
Thanks
Allan

private class MyFileChooser extends JFileChooser
    {
        public MyFileChooser()
        {
            super();
        }

        public MyFileChooser(String baseDir)
        {
            super(baseDir);
        }

        public void approveSelection()
        {
            if(!validateFile(this.getSelectedFile()))
            {
                //show some error message
                return;//the FileChooser wont close until and unless u call
super.approveSelection()
            }
            super.approveSelection();
        }

   private boolean validateFile(File file)
        {
            //do your validation here
            if (file.exists())
            {
                if (JOptionPane.showConfirmDialog(null, "File exists,
overwrite?", "Overwrite File?", JOptionPane.YES_NO_OPTION) ==
JOptionPane.YES_OPTION)
                    return true;
                return false;
            }
            else
  return true;
        }
    }