JFileChooser is a part of java Swing package. The java Swing package is part of JavaTM Foundation Classes(JFC) . JFC contains many features that help in building graphical user interface in java . Java Swing provides components such as buttons, panels, dialogs, etc . JFileChooser is a easy and an effective way to prompt the user to choose a file or a directory .Â
In this article we will see how to use JFileChooser in java swing .
Constructors of JFileChooser are :Â
Â
1. JFileChooser() – empty constructor that points to user’s default directoryÂ
Â
Java
// Using this process to invoke the constructor,// JFileChooser points to user's default directoryJFileChooser j = new JFileChooser();Â
// Open the save dialogj.showSaveDialog(null); |
Output of the code snippet:Â
Â
Â
2. JFileChooser(String) – uses the given pathÂ
Â
Java
// Using this process to invoke the constructor,// JFileChooser points to the mentioned pathJFileChooser j = new JFileChooser("d:");Â
// Open the save dialogj.showSaveDialog(null); |
Output of the code snippet:Â
Â
Â
3. JFileChooser(File) – uses the given File as the pathÂ
Â
Java
// Using this process to invoke the constructor,// JFileChooser points to the mentioned path// of the file passedJFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New folder\\"));Â
// Open the save dialogj.showSaveDialog(null); |
Output of the code snippet:Â
Â
4. JFileChooser(FileSystemView) – uses the given FileSystemViewÂ
Â
Java
// In this process argument passed// is an object of File System ViewJFileChooser j = new JFileChooser(FileSystemView.getFileSystemView());Â
// Open the save dialogj.showSaveDialog(null); |
Output of the code snippet:Â
Â
5. JFileChooser(String, FileSystemView) – uses the given path and the FileSystemView
Â
Java
// In this process argument passed is an object// of File System View, and a pathJFileChooser j = new JFileChooser("d:", FileSystemView.getFileSystemView());Â
// Open the save dialogj.showSaveDialog(null); |
Output of the code snippet:Â
Â
6. JFileChooser(File, FileSystemView) – uses the given current directory and the FileSystemViewÂ
Â
Java
// In this process argument passed is an object// of File System View and a object of// File classFile f = new File("C:\\Users\\pc\\Documents\\New folder\\");JFileChooser j = new JFileChooser(f, FileSystemView.getFileSystemView());Â
// Open the save dialogj.showSaveDialog(null); |
Output of the code snippet:Â
Â
Note : The code given above are code snippets not the full code, the code snippets given above should be used to invoke the constructor as per the need and discretion of the programmer, the paths mentioned above are arbitrary. User should set the path according to their need.
Â
Practical Applications of JFileChooser
The following codes will not execute in an online compiler. Please use an offline IDEÂ
1. Creating an open or save dialog using JFileChooserÂ
Â
Java
// Java program to create open or// save dialog using JFileChooserimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener {Â
    // Jlabel to show the files user selects    static JLabel l;Â
    // a default constructor    filechooser()    {    }Â
    public static void main(String args[])    {        // frame to contains GUI elements        JFrame f = new JFrame("file chooser");Â
        // set the size of the frame        f.setSize(400, 400);Â
        // set the frame's visibility        f.setVisible(true);Â
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Â
        // button to open save dialog        JButton button1 = new JButton("save");Â
        // button to open open dialog        JButton button2 = new JButton("open");Â
        // make an object of the class filechooser        filechooser f1 = new filechooser();Â
        // add action listener to the button to capture user        // response on buttons        button1.addActionListener(f1);        button2.addActionListener(f1);Â
        // make a panel to add the buttons and labels        JPanel p = new JPanel();Â
        // add buttons to the frame        p.add(button1);        p.add(button2);Â
        // set the label to its initial value        l = new JLabel("no file selected");Â
        // add panel to the frame        p.add(l);        f.add(p);Â
        f.show();    }    public void actionPerformed(ActionEvent evt)    {        // if the user presses the save button show the save dialog        String com = evt.getActionCommand();Â
        if (com.equals("save")) {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // invoke the showsSaveDialog function to show the save dialog            int r = j.showSaveDialog(null);Â
            // if the user selects a file            if (r == JFileChooser.APPROVE_OPTION)Â
            {                // set the label to the path of the selected file                l.setText(j.getSelectedFile().getAbsolutePath());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }Â
        // if the user presses the open dialog show the open dialog        else {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // invoke the showsOpenDialog function to show the save dialog            int r = j.showOpenDialog(null);Â
            // if the user selects a file            if (r == JFileChooser.APPROVE_OPTION)Â
            {                // set the label to the path of the selected file                l.setText(j.getSelectedFile().getAbsolutePath());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }    }} |
2. Use JFileChooser to select directory onlyÂ
Â
Java
// Java program to use JFileChooser// to select directory onlyimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener {    // Jlabel to show the files user selects    static JLabel l;Â
    // a default constructor    filechooser()    {    }Â
    public static void main(String args[])    {        // frame to contains GUI elements        JFrame f = new JFrame("file chooser to select directories");Â
        // set the size of the frame        f.setSize(400, 400);Â
        // set the frame's visibility        f.setVisible(true);Â
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Â
        // button to open save dialog        JButton button1 = new JButton("save");Â
        // button to open open dialog        JButton button2 = new JButton("open");Â
        // make an object of the class filechooser        filechooser f1 = new filechooser();Â
        // add action listener to the button to capture user        // response on buttons        button1.addActionListener(f1);        button2.addActionListener(f1);Â
        // make a panel to add the buttons and labels        JPanel p = new JPanel();Â
        // add buttons to the frame        p.add(button1);        p.add(button2);Â
        // set the label to its initial value        l = new JLabel("no file selected");Â
        // add panel to the frame        p.add(l);        f.add(p);Â
        f.show();    }    public void actionPerformed(ActionEvent evt)    {        // if the user presses the save button show the save dialog        String com = evt.getActionCommand();Â
        if (com.equals("save")) {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // set the selection mode to directories only            j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);Â
            // invoke the showsSaveDialog function to show the save dialog            int r = j.showSaveDialog(null);Â
            if (r == JFileChooser.APPROVE_OPTION) {                // set the label to the path of the selected directory                l.setText(j.getSelectedFile().getAbsolutePath());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }        // if the user presses the open dialog show the open dialog        else {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // set the selection mode to directories only            j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);Â
            // invoke the showsOpenDialog function to show the save dialog            int r = j.showOpenDialog(null);Â
            if (r == JFileChooser.APPROVE_OPTION) {                // set the label to the path of the selected directory                l.setText(j.getSelectedFile().getAbsolutePath());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }    }} |
3. Use JFileChooser to allow multiple selection of filesÂ
Â
Java
// Java program to use JFileChooser to allow multiple selection of filesimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener {    // Jlabel to show the files user selects    static JLabel l;Â
    // a default constructor    filechooser()    {    }Â
    public static void main(String args[])    {        // frame to contains GUI elements        JFrame f = new JFrame("file chooser to select multiple files at a time");Â
        // set the size of the frame        f.setSize(400, 400);Â
        // set the frame's visibility        f.setVisible(true);Â
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Â
        // button to open save dialog        JButton button1 = new JButton("save");Â
        // button to open open dialog        JButton button2 = new JButton("open");Â
        // make an object of the class filechooser        filechooser f1 = new filechooser();Â
        // add action listener to the button to capture user        // response on buttons        button1.addActionListener(f1);        button2.addActionListener(f1);Â
        // make a panel to add the buttons and labels        JPanel p = new JPanel();Â
        // add buttons to the frame        p.add(button1);        p.add(button2);Â
        // set the label to its initial value        l = new JLabel("no file selected");Â
        // add panel to the frame        p.add(l);        f.add(p);Â
        f.show();    }    public void actionPerformed(ActionEvent evt)    {        // if the user presses the save button show the save dialog        String com = evt.getActionCommand();Â
        if (com.equals("save")) {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // allow multiple file selection            j.setMultiSelectionEnabled(true);Â
            // invoke the showsSaveDialog function to show the save dialog            int r = j.showSaveDialog(null);Â
            if (r == JFileChooser.APPROVE_OPTION) {                // get the Selected files                File files[] = j.getSelectedFiles();Â
                int t = 0;                // set text to blank                l.setText("");Â
                // set the label to the path of the selected files                while (t++ < files.length)                    l.setText(l.getText() + " " + files[t - 1].getName());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }Â
        // if the user presses the open dialog show the open dialog        else {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // allow multiple file selection            j.setMultiSelectionEnabled(true);Â
            // invoke the showsOpenDialog function to show the save dialog            int r = j.showOpenDialog(null);Â
            if (r == JFileChooser.APPROVE_OPTION) {                // get the Selected files                File files[] = j.getSelectedFiles();Â
                // set text to blank                l.setText("");Â
                int t = 0;                // set the label to the path of the selected files                while (t++ < files.length)                    l.setText(l.getText() + " " + files[t - 1].getName());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }    }} |
4. Use JFileChooser to restrict the type of files shown to the userÂ
Â
Java
// Java program to use JFileChooser to restrict// the type of files shown to the userimport java.io.*;import javax.swing.*;import java.awt.event.*;import javax.swing.filechooser.*;class filechooser extends JFrame implements ActionListener {    // Jlabel to show the files user selects    static JLabel l;Â
    // a default constructor    filechooser()    {    }Â
    public static void main(String args[])    {        // frame to contains GUI elements        JFrame f = new JFrame("file chooser");Â
        // set the size of the frame        f.setSize(400, 400);Â
        // set the frame's visibility        f.setVisible(true);Â
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Â
        // button to open save dialog        JButton button1 = new JButton("save");Â
        // button to open open dialog        JButton button2 = new JButton("open");Â
        // make an object of the class filechooser        filechooser f1 = new filechooser();Â
        // add action listener to the button to capture user        // response on buttons        button1.addActionListener(f1);        button2.addActionListener(f1);Â
        // make a panel to add the buttons and labels        JPanel p = new JPanel();Â
        // add buttons to the frame        p.add(button1);        p.add(button2);Â
        // set the label to its initial value        l = new JLabel("no file selected");Â
        // add panel to the frame        p.add(l);        f.add(p);Â
        f.show();    }    public void actionPerformed(ActionEvent evt)    {        // if the user presses the save button show the save dialog        String com = evt.getActionCommand();Â
        if (com.equals("save")) {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // restrict the user to select files of all types            j.setAcceptAllFileFilterUsed(false);Â
            // set a title for the dialog            j.setDialogTitle("Select a .txt file");Â
            // only allow files of .txt extension            FileNameExtensionFilter restrict = new FileNameExtensionFilter("Only .txt files", "txt");            j.addChoosableFileFilter(restrict);Â
            // invoke the showsSaveDialog function to show the save dialog            int r = j.showSaveDialog(null);Â
            // if the user selects a file            if (r == JFileChooser.APPROVE_OPTION)Â
            {                // set the label to the path of the selected file                l.setText(j.getSelectedFile().getAbsolutePath());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }        // if the user presses the open dialog show the open dialogÂ
        else {            // create an object of JFileChooser class            JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());Â
            // restrict the user to select files of all types            j.setAcceptAllFileFilterUsed(false);Â
            // set a title for the dialog            j.setDialogTitle("Select a .txt file");Â
            // only allow files of .txt extension            FileNameExtensionFilter restrict = new FileNameExtensionFilter("Only .txt files", "txt");            j.addChoosableFileFilter(restrict);Â
            // invoke the showsOpenDialog function to show the save dialog            int r = j.showOpenDialog(null);Â
            // if the user selects a file            if (r == JFileChooser.APPROVE_OPTION) {                // set the label to the path of the selected file                l.setText(j.getSelectedFile().getAbsolutePath());            }            // if the user cancelled the operation            else                l.setText("the user cancelled the operation");        }    }} |
NOTE :Â
you can also customize the approve button by using the function setApproveButtonText(String) . This will set the text of the approved buttonÂ
to the desired text.
Â

