Using the JFileChooser

  1. To use the JFileChooser you just need to import javax.swing.* (which you probably already did).
  2. You can construct a new JFileChooser like so:
    JFileChooser chooser = new JFileChooser([startDir]);
    

    Note: startDir is optional, but if you use it, in place of [startDir] you actually need to say new File(startDir).getAbsolutePath(). You would want to do this if you expected the user to open the file chooser more than once and would want the dialog to remember the last directory they were in.

  3. Next, you can open the file chooser like so:
    int ret = chooser.showOpenDialog(this);
    

    Other choices are: .showSaveDialog(), or just .showDialog() (which allows you to make a "custom" file chooser)

  4. Test the return code with an 'if' statement, for example:
    if (ret == JFileChooser.APPROVE_OPTION)
    

    Other choices are: CANCEL_OPTION (they hit the cancel button), or ERROR_OPTION (there was some kind of error or the dialog was closed via the little 'x' button in the corner).

  5. If the return code was the APPROVE_OPTION, you can get the file that was selected like so:
    File file = chooser.getSelectedFile();
    
  6. Now you can do whatever with the file: get it's name, it's cannonical path, etc.