-2

I would build a panel which let me choose where I can save a file. I read java documentation and I saw that there is a swing component named file chooser but I don't know how use it.what i want to do is choose the path in my machine where saved a file created.

Mazzy
  • 13,354
  • 43
  • 126
  • 207

2 Answers2

2

How to use it? Well, you just need to "use it"! Really!

This will create your FileChooser instance and set it to start at user's desktop folder:

JFileChooser fc = new JFileChooser(System.getProperty("user.home") + "/Desktop");

After that, you can set a variety of options. In this case, i'm setting it up to allow choosing multiple files, and only ".xls" (Excel) files:

fc.setMultiSelectionEnabled(true);

SelectionEnabled(true);
        FileFilter ff = new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }
                String extension = f.getName().substring(f.getName().lastIndexOf("."));
                if (extension != null) {
                    if (extension.equalsIgnoreCase(".xls")) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }

            @Override
            public String getDescription() {
                return "Arquivos Excel (\'.xls\')";
            }
        };
fc.setFileFilter(ff);

And finally, i'm showing it up and getting the user's choice and chosen files:

File[] chosenFiles;
int choice = fc.showOpenDialog(fc);
        if (choice == JFileChooser.APPROVE_OPTION) {
            chosenFiles = fc.getSelectedFiles();
        } else {
        //User canceled. Do whatever is appropriate in this case.
        }

Enjoy! And good luck!

CosmicGiant
  • 6,275
  • 5
  • 43
  • 58
1

This tutorial, straight from the Oracle website, is a great place to start learning about FileChoosers.

final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);

if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    //This is where a real application would open the file.
    log.append("Opening: " + file.getName() + ".");
} else {
    log.append("Open command cancelled by user.");
}

The above code opens a FileChooser, and stores the selected file in the fc variable. The selected button (OK, Cancel, etc) is stored in returnVal. You can then do whatever you wish with the file.

adchilds
  • 963
  • 2
  • 9
  • 22
  • You're too kind, adchilds. There are a million links for using JFileChooser(). One addendum: if you want "directories only", add `fc.setFileSelectionMode(JFileChooser.DIRECTORIES);`. – paulsm4 Jul 13 '12 at 19:37