Tóm Tắt
Show simple open file dialog using JFileChooser
- Details
- Written by Nam Ha Minh
-
Last Updated on 06 July 2019   |  
Print
Email
The steps to create a simple open file dialog using JFileChooser class are as follows:
- Add required import statements:
import javax.swing.JFileChooser; import java.io.File;
- Create a new instance of
JFileChooser
class:
JFileChooser fileChooser = new JFileChooser();
- 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.
- Show up the dialog:
int result = fileChooser.showOpenDialog(parent);
where
parent
is an instance of a
Component
such as
JFrame
,
JDialog
or
JPanel
which is parent of the dialog.
- Check if the user selects a file or not:
If the user selects a file, the variable result will hold a value ofJFileChooser.APPROVE_OPTION
. So it’s necessary to check return value of the method
showOpenDialog()
:
if (result == JFileChooser.APPROVE_OPTION) { // user selects a file }
- Pick up the selected file:
File selectedFile = fileChooser.getSelectedFile();
- 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:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.