The Wayback Machine - https://web.archive.org/web/20241005000140/https://www.geeksforgeeks.org/java-swing-jfilechooser/
Open In App

Java Swing | JFileChooser

Last Updated : 01 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 directory
JFileChooser j = new JFileChooser();
 
// Open the save dialog
j.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 path
JFileChooser j = new JFileChooser("d:");
 
// Open the save dialog
j.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 passed
JFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New folder\\"));
 
// Open the save dialog
j.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 View
JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView());
 
// Open the save dialog
j.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 path
JFileChooser j = new JFileChooser("d:", FileSystemView.getFileSystemView());
 
// Open the save dialog
j.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 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);


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 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");
        }
    }
}


2. Use JFileChooser to select directory only 
 

Java




// 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");
        }
    }
}


3. Use JFileChooser to allow multiple selection of files 
 

Java




// 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 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 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());
 
            // 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.
 



Similar Reads

Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java Swing | ScrollPaneLayout Class
The layout manager used by JScrollPane. JScrollPaneLayout is based on nine components: a viewport, two scrollbars, a row header, a column header, and four "corner" components. Constructor of the class: ScrollPaneLayout(): It is used to Construct a new ScrollPaneLayout. Commonly Used Methods: removeLayoutComponent(Component comp): Removes the specif
4 min read
Java Swing - JPanel With Examples
JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar. Constructors of JPanel JPanel(): creates a new panel with a flow layoutJPanel(L
4 min read
Java Swing | Internal Frame with examples
JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc. Constructors for JInternalFrame JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with n
8 min read
Java Swing | JTextField
JTextField is a part of javax.swing package. The class JTextField is a component that allows editing of a single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants.The constructor of the class are : JTextField() : constructor that creates a new TextFieldJTextField(int columns) : constructor that creates
5 min read
Java Swing | JProgressBar
JProgressBar is a part of Java Swing package. JProgressBar visually displays the progress of some specified task. JProgressBar shows the percentage of completion of specified task.The progress bar fills up as the task reaches it completion. In addition to show the percentage of completion of task, it can also display some text .Constructors of JPro
4 min read
JLabel | Java Swing
JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both . JLabel is only a display of text or image and it cannot get focus . JLabel is inactive to input events such a mouse focus or keyboard focus. By default labels are vertically centered but the user can change the align
4 min read
Java Swing | JToolBar
JToolBar is a part of Java Swing package. JToolBar is an implementation of toolbar. The JToolBar is a group of commonly used components such as buttons or drop down menu. JToolBar can be dragged to different locations by the user Constructors of the class are: JToolBar() : creates a new toolbar with horizontal orientationJToolBar(int o) : creates a
6 min read
JRadioButton | Java Swing
We use the JRadioButton class to create a radio button. Radio button is use to select one option from multiple options. It is used in filling forms, online objective papers and quiz. We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use "ButtonGroup" class to create a ButtonGroup and add radio button in
6 min read
Java Swing | ToolTip
We can add tooltip text to almost all the components of Java Swing by using the following method setToolTipText(String s). This method sets the tooltip of the component to the specified string s. When the cursor enters the boundary of that component a popup appears and text is displayed. Methods used: getToolTipText() : returns the tooltip text for
4 min read
Java Swing | JSlider
JSlider is a part of Java Swing package . JSlider is an implementation of slider. The Component allows the user to select a value by sliding the knob within the bounded value . The slider can show Major Tick marks and also the minor tick marks between two major tick marks, The knob can be positioned at only those points. Constructor of the class ar
6 min read
Java Swing | JSplitPane with Examples
JSplitPane is a part of Java Swing. JSplitPane is used to divide only two components. JSplitPane is to use resize the components . By using the JSplitPane the user can manually resize the component till its minimum size . JSplitPane can be of two types, one is the vertical and horizontal splitpane Constructor of JSplitPane are: JSplitPane() : creat
6 min read
Java Swing | JComboBox with examples
JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .Constructor of the JComboBox are: JComboBox() : creates a new empty JComboBox .
7 min read
Java Swing | Simple Calculator
Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle's Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java Programs.Swing was created to provide more powerful and flexible components than Java AWT (Abstract Window Toolkit).In this article we will us
4 min read
Java Swing | JCheckBox with examples
JCheckBox is a part of Java Swing package . JCheckBox can be selected or deselected . It displays it state to the user . JCheckBox is an implementation to checkbox . JCheckBox inherits JToggleButton class. Constructor of the class are : JCheckBox() : creates a new checkbox with no text or icon JCheckBox(Icon i) : creates a new checkbox with the ico
5 min read
Java Swing | JDialog with examples
JDialog is a part Java swing package. The main purpose of the dialog is to add components to it. JDialog can be customized according to user need .Constructor of the class are: JDialog() : creates an empty dialog without any title or any specified ownerJDialog(Frame o) :creates an empty dialog with a specified frame as its ownerJDialog(Frame o, Str
5 min read
Java Swing | JWindow with examples
JWindow is a part of Java Swing and it can appear on any part of the users desktop. It is different from JFrame in the respect that JWindow does not have a title bar or window management buttons like minimize, maximize, and close, which JFrame has. JWindow can contain several components such as buttons and labels. Constructor of the class are: JWin
5 min read
Java Swing | Creating a Toast Message
What are toast messages? And how to create them by using Java Swing? Toast Messages are a quick way of informing the user by short Pop-up messages that last for a short period of time and then disappear. Java Swing does not have an inbuilt class for toast message but toast message is a popular and an effective way to display auto-expiring message t
3 min read
Java Swing | JList with examples
JList is part of Java Swing package . JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class. JList is a easy way to display an array of Vectors .Constructor for JList are : JList(): creates an empty blank listJList(E [ ] l) : creates an new list with the elements of the
4 min read
Java Swing | JTable
The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.Constructors in JTable: JTable(): A table is created with empty cells.JTable(int rows, int cols): Creates a table of size rows * col
2 min read
Java Swing | BevelBorder and SoftBevelBorder
BevelBorder and SoftBevelBorder are a part of javax.swing.Border package. This package contains different Border for Components. BevelBorder is an implementation of a simple two line bevel border. Bevel Border and Soft Bevel Border are almost same but Soft Bevel Border has softened corners.Constructor for the class BevelBorder: BevelBorder(int Type
7 min read
Java Swing | MatteBorder
MatteBorder is a class which is used to make a matte-like border of either a solid color or a tiled icon. It is a part of javax.swing.border package and contains different styles of Borders for Components. This class helps us to set an icon or a solid color as a border and the insets of the border can also be applied using this class.Constructor of
5 min read
Java Swing | Popup and PopupFactory with examples
Popup and PopupFactory are a part of the Java Swing library. Popups are used when we want to display to the user a Component on the top of all the other Components in that particular containment hierarchy. PopupFactory is the class that is used to create popups. Popups have a very small life cycle, and generally are lightweight components having li
5 min read
Java Swing | JSeparator with examples
JSeparator is a part of Java Swing framework. It is used to create a dividing line between two components. More specifically, it is mainly used to create dividing lines between menu items in a JMenu. In JMenu or JPopupMenu addSeparartor function can also be used to create a separator. Constructor of the class are: separator(): Creates a new horizon
4 min read
Java Swing | JToggleButton Class
A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices. Buttons can be configured, and to so
4 min read
Java Swing | GroupLayout Class
GroupLayout is a LayoutManager that hierarchically group the components and arranges them in a Container. Grouping is done by using the instances of the Group class. It is generally used for developing a GUI ( Graphic User Interface) builders such as Matisse, the GUI builder provided with the NetBeans IDE. GroupLayout Class supports two types of gr
6 min read
Java Swing | JColorChooser Class
JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. This class provides three levels of API: A static convenience method that shows a modal color-chooser dialog and returns the color selected by the user.A static convenience method for creating a color-chooser dialog where ActionListeners can be spec
5 min read
Difference between AWT and Swing in Java
Java is one of the most in-demand programming languages for developing a variety of applications. The popularity of Java can be attributed to its versatility as it can be used to design customized applications that are light and fast and serve a variety of purposes ranging from web services to android applications. Java is fast, reliable, and secur
2 min read
Student Grade Calculator using Java Swing
Consider the following scenario. We need to create a GUI based application which calculates grade of students according to marks obtained in 4 subjects. Below are the range of marks for different grades. MarksGrade>90%ABetween 85% - 90%BBetween 80% - 85%CBetween 70% - 80%DBetween 60% - 70%EBetween 50% - 60%Poor We will be using Netbeans to creat
4 min read
Article Tags :
Practice Tags :