The steps to create a simple open file dialog using JFileChooser class are as follows:

  1. Add required import statements:
            import javax.swing.JFileChooser;
            import java.io.File;        
            
  2. Create a new instance ofJFileChooser class:
            JFileChooser fileChooser = new JFileChooser();
            
  3. Set current directory:
            fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
            
    The current directory is initial directory where the dialog looks for files. The above line sets the current directory to user’s home directory.

     

  4. Show up the dialog:
            
            int result = fileChooser.showOpenDialog(parent);
    where parent is an instance of a Component such as JFrame, JDialog or JPanelwhich is parent of the dialog.

     

  5. Check if the user selects a file or not:
    If the user selects a file, the variable result will hold a value of JFileChooser.APPROVE_OPTION. So it’s necessary to check return value of the method showOpenDialog():
            
            if (result == JFileChooser.APPROVE_OPTION) {
                // user selects a file
            }
  6. Pick up the selected file:
            
                File selectedFile = fileChooser.getSelectedFile();
  7. And the whole code snippet is as follows:
            
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
            int result = fileChooser.showOpenDialog(this);
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                System.out.println("Selected file: " + selectedFile.getAbsolutePath());
            } 

 

Related Swing File Chooser Tutorials:

 

Other Java Swing Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#22Satan2021-04-19 08:39
Can't believe it works, thank God
Quote
#21Olaf2018-10-16 02:08
What should I do if I want to use the "this"?
Quote
#20Alice Chen2018-10-11 19:45
Thank you! This is so clear and works well!
Quote
#19Daniel2018-07-21 03:19
THIS is exactly how "manuals" should be written.
KUDOS!
Quote
#18Nam2016-08-12 12:00
Quoting bhavani:
Hi what is parent referring to in below:
int result = fileChooser.showOpenDialog(parent);


Parent can be a frame, a dialog or a panel.
Quote