Java Swing | JFileChooser

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
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Using this process to invoke the contructor,
    // JFileChooser points to user's default directory
    JFileChooser j = new JFileChooser();
      
    // Open the save dialog
    j.showSaveDialog(null);

    chevron_right

    
    

    Output of the code snippet:

  2. JFileChooser(String) – uses the given path
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Using this process to invoke the constructor,
    // JFileChooser points to the mentioned path
    JFileChooser j = new JFileChooser("d:");
      
    // Open the save dialog
    j.showSaveDialog(null);

    chevron_right

    
    

    Output of the code snippet:

  3. JFileChooser(File) – uses the given File as the path
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Using this process to invoke the constructor,
    // JFileChooser points to the mentioned path
    // of the file passed
    JFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New folder\\"));
      
    // Open the save dialog
    j.showSaveDialog(null);

    chevron_right

    
    

    Output of the code snippet:

  4. JFileChooser(FileSystemView) – uses the given FileSystemView
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // In this process argument passed
    // is an object of File System View
    JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView());
      
    // Open the save dialog
    j.showSaveDialog(null);

    chevron_right

    
    

    Output of the code snippet:

  5. JFileChooser(String, FileSystemView) – uses the given path and the FileSystemView
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // In this process argument passed is an object
    // of File System View, and a path
    JFileChooser j = new JFileChooser("d:", FileSystemView.getFileSystemView());
      
    // Open the save dialog
    j.showSaveDialog(null);

    chevron_right

    
    

    Output of the code snippet:

  6. JFileChooser(File, FileSystemView) – uses the given current directory and the FileSystemView
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // In this process argument passed is an object
    // of File System View and a object of
    // File class
    File f = new File("C:\\Users\\pc\\Documents\\New folder\\");
    JFileChooser j = new JFileChooser(f, FileSystemView.getFileSystemView());
      
    // Open the save dialog
    j.showSaveDialog(null);

    chevron_right

    
    

    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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to create open or
// save dialog using JFileChooser
import 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");
        }
    }
}

chevron_right



2. Use JFileChooser to select directory only

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to use JFileChooser
// to select  directory only
import 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");
        }
    }
}

chevron_right




3. Use JFileChooser to allow multiple selection of files

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to use JFileChooser to allow multiple selection of files
import 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 selelcted 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 selelcted 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");
        }
    }
}

chevron_right



4. Use JFileChooser to restrict the type of files shown to the user

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to use JFileChooser to restrict
// the type of files shown to the user
import 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());
  
            // resctrict the user to selec 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());
  
            // resctrict the user to selec 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");
        }
    }
}

chevron_right



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.



My Personal Notes arrow_drop_up

Second year Department of Information Technology Jadavpur University

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.