by Dinesh Thakur

Some operating systems have some special dialog boxes including selection to handle things like fonts, colors, printers and the like. Virtually all operating systems support the opening and storage of files, however, and thus the Java JFileChooser encapsulates this for easy use. JFileChooser, Opens a dialog box to ask for a filename.

For a dialog "open file", called showOpenDialog (), and a dialogue of "save file" is called showSaveDialog (). these commands do not return until the dialog box is closed. the object JFileChooser still exists, so you can read the data. the getSelectedFile () method and GetCurrentDirectory () are two ways in which can examine the results of the operation. If these return null means that the user canceled the dialog.

Here is the example of JFileChooser

import java.awt.*;
import java.io.File;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
public class JavaExampleFileChooserInJavaSwing extends JFrame implements ActionListener
{
    JFileChooser Chsr = new JFileChooser();
    JButton BtnFileChsr = new JButton("Show File Chooser");
    JTextField Txt = new JTextField(25);
    public JavaExampleFileChooserInJavaSwing()
      {
           super("Example Of File Chooser In Java Swing");
           Container Cntnr = getContentPane();
           Cntnr.setLayout(new FlowLayout());
           Cntnr.add(BtnFileChsr);       
           Cntnr.add(Txt);       
           BtnFileChsr.addActionListener(this);
     }
          public void actionPerformed(ActionEvent e)
           {
              int Rslt = Chsr.showOpenDialog(null);
              File Flobj1 = Chsr.getSelectedFile();
              if(Rslt == JFileChooser.APPROVE_OPTION)
               {
                    Txt.setText("You Select " + Flobj1.getPath());
                   }
                    else if(Rslt == JFileChooser.CANCEL_OPTION)
                         {
                                 Txt.setText("You Pressed Cancel");
                             }
          }
                       public static void main(String ag[])
                        {
                             JFrame Frm = new JavaExampleFileChooserInJavaSwing();
                             Frm.setBounds(210,210,410,210);
                             Frm.setVisible(true);
                             Frm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                             Frm.addWindowListener(new WindowAdapter()
                           {
                                      public void windowClosing(WindowEvent e1)
                                         {
                                             System.exit(0);   
                                         }
                                   });
                      }
 }

JFileChooser Java Swing Example