Displaying a dialog window to open files

This following example will use Swings JFileChooser to display a dialog box and allow the user to select a file.
It will set the current directory to c: and set the default selection to autoexec.bat. Notice that multiple file selections are not implemented for the current look and feels (see the JFileChooser API).
The method showOpenDialog will block until a file has been selected. It returns APPROVE_OPTION if OK has been clicked, CANCEL_OPTION otherwise.

import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class Main extends JFrame
{
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }

   public Main() {
      JButton fileButton = new JButton("Select File");
      fileButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            File file = getFileFromUser();
            if (file != null)
               System.out.println(file.getName());
         }
      });
      getContentPane().add(fileButton);

      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });

      pack();
   }
  
   public File getFileFromUser() {
      JFileChooser fc = new JFileChooser();

      // use current directory
      fc.setCurrentDirectory(new File("c:\"));

      // set default name
      fc.setSelectedFile(new File("autoexec.bat"));

      // enable multiple selection, not implemented yet in current L&F's
      fc.setMultiSelectionEnabled(true);

      // show dialog for opening files
      int result = fc.showOpenDialog(this);

      if (result != fc.APPROVE_OPTION) 
         return null;
      
      return fc.getSelectedFile();
   }
}