Jon Snow
Jon Snow

Reputation: 461

Get how many files a user choose using JFileChooser

In my program I am using a JFileChooser. The user can select multiple files using the JFileChooser. If the user selects only one file, only a File object is returned, and is retrieveable using fileChooser.getSelectedFile(). If the user selects more than one file, a File[] is returned, and is retrievable using fileChooser.getSelectedFiles().

At the moment I am using a try/catch block to grab whatever type is returned using said methods. I feel as if this is a bad way of doing it.

Is there any way to check what type of object will be returned (e.g whether I should receive an Array)? I can't seem to find a method in the API to do so.

Upvotes: 1

Views: 546

Answers (2)

Leon
Leon

Reputation: 1141

if you want to make sure only certain types of files can be selected you should set a file filter

    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new FileFilter()
    {
      public boolean accept(File file)
      {
        return file.isDirectory() ||
               file.getName().endsWith(".abc");
      }
      public String getDescription()
      {
        return "Your files *.abc files";
      }
    });

Upvotes: 1

woliveirajr
woliveirajr

Reputation: 9483

If you allow user to select more than one file, them you should call the get.SelectedFiles() and receive an array as answer.

Since it's an array, you can see the numbers of components to see how many files were selected (one, two...) and them interact through it to do anything you want.

And if you discover that it received just one file, act like you want.

Upvotes: 4

Related Questions