Adding a File Chooser to a Java Application

This tutorial needs a review. You can open a JIRA issue, or edit it in GitHub following these contribution guidelines.

Contributed by Petr Dvorak (Dec 2009), maintained by Alyona Stashkova

This tutorial shows how to add a file chooser to a Java application using the javax.swing.JFileChooser component. You could code it all by hand, but using the NetBeans GUI Builder is a smart way that will save you a bit of work. As part of the exercise, you will create a small Java application that loads a .txt file into a Text Area.

netbeans stamp 80 74 73
Figure 1. Content on this page applies to the NetBeans IDE 7.0 and more recent

To complete this tutorial, you need the following software and resources.

Software or Resource Version Required

NetBeans IDE

Version 7.0 or more recent

Java Development Kit (JDK)

Version 6, 7, or 8

Creating the Application

First you create a new Java Application:

  1. From the main menu, choose File > New Project. Choose the Java category and the Java Application project type. Click Next.

  2. For Project Name, type JFileChooserDemo and specify the project location.

  3. Deselect the Create Main Class checkbox.

newproj small
  1. Click Finish.

Creating the Application Form

In this section, you create a JFrame container and add a few components to it.

To create the JFrame form:

  1. Right-click the Source Packages node and choose New > Other. Choose the Swing GUI Forms category and the JFrameForm file type. Click Next.

  2. For Class Name, type JFileChooserDemo.

  3. For Package, type jfilechooserdemo.resources.

newjframeform small
  1. Click Finish.

  2. In the Properties window, enter Demo application for the Title property and press Enter to confirm.

To add components to the JFrame form:

  1. In the Palette, open the Swing Menus category, select the Menu Bar component and drag it to the left top corner of the JFrame.

*Note: * If you do not see the Palette, select Window > Palette from the main menu.

menubaradded small
  1. Right-click the Edit item of the Menu Bar component and select Delete in the context menu.

  2. To add a menu item that allows to open FileChooser from the running application, in the Swing Menus category in the Palette, select a new Menu Item (JMenuItem1), drag it to the Menu Bar, and drop it to the File item of the Menu Bar.

menuitemadded small

*Note: * Make sure the Menu Bar is selected before dragging another Menu Item there in order to have the latter added to the Menu Bar.

  1. Right-click the jMenuItem1 in the Design view and choose Change Variable Name from the context menu. Rename the item to Open and click OK.

  2. Make sure that the jMenuItem1 is still selected in the Design view. Press the Space bar to edit the text of the component. Change the text to Open and press Enter to confirm.

  3. Specify the action handler for the Open menu item. Right-click the menu item and choose Events > Action > action Performed from the context menu. The GUI Builder automatically switches to the Source view and a new event handler method named OpenActionPerformed() is generated. The Navigator window should look as follows:

openactionperformednavigator
  1. To add a menu item to exit FileChooser from the application being created, switch back into the Design mode, in the Swing Menus category in the Palette, select a Menu Item (JMenuItem1) and drag it to the Menu Bar below the Open menu item. Notice orange highlighting that indicates where the JMenuItem1 is going to be placed.

highlighting small
  1. Right-click jMenuItem1 in the Design view and choose Change Variable Name from the context menu. Rename the item to Exit and click OK.

  2. Make sure that the jMenuItem1 is still selected in the Design view. Press the Space bar to edit the text of the component. Change the text to Exit and press Enter to confirm.

  3. Specify the action handler for the Exit menu item. Right-click the menu item and choose Events > Action > action Performed from the context menu. The GUI Builder automatically switches to the Source view and a new event handler method is generated which is named ExitActionPerformed().The ExitActionPerformed node appears in the Navigator window below the OpenActionPerformed() node.

  4. To make the Exit menu item work, you include the following source into the ExitActionPerformed() method body:

			 System.exit(0);
  1. Switch back into Design mode. From the Swing Controls category of the Palette, drag a Text Area ( JTextArea ) into the form like shown in the picture below.

textareadded small
  1. Resize the added component to make room for the text displayed by the File Chooser later. Rename the variable to textarea. The form should look like the following screenshot:

jfilechooserdemoview final small

You have set up a simple Java application as a base for this tutorial. Next you add the actual File Chooser.

Adding the File Chooser

  1. Choose Window > Navigating > Navigator to open the Navigator window, if it is not open yet.

  2. In the Navigator, right-click the Other Components node. Choose Add From Palette > Swing Windows > File Chooser from the context menu

As an alternative to the Add From Palette context menu, you can also drag and drop a JFileChooser component from the Swing Window category of the Palette to the white area of the GUI builder. It will have the same result, but it is a bit harder, because the preview of the JFileChooser is rather big and you might accidentally insert the window into one of the panels, which is not what you want.

  1. A look in the Navigator confirms that a JFileChooser was added to the form.

  2. Right-click the JFileChooser node and rename the variable to fileChooser.

navigator jframe

You have added a File Chooser. Next you tune the File Chooser to display the title that you want, add a custom file filter, and integrate the File Chooser into your application.

Configuring the File Chooser

Implementing the Open Action

  1. Click to select the JFileChooser in the Navigator window, and then edit its properties in the Properties dialog box. Change the dialogTitle property to This is my open dialog, press Enter and close the Properties dialog box.

  2. Click the Source button in the GUI Builder to switch to the Source mode. To integrate the File Chooser into your application, paste the following code snippet into the existing OpenActionPerformed() method.

private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
    int returnVal = fileChooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        try {
          // What to do with the file, e.g. display it in a TextArea
          textarea.read( new FileReader( file.getAbsolutePath() ), null );
        } catch (IOException ex) {
          System.out.println("problem accessing file"+file.getAbsolutePath());
        }
    } else {
        System.out.println("File access cancelled by user.");
    }
}

*Note: * Remove the first and last lines of the code snippet that duplicate the existing ones in the source file.

  1. If the editor reports errors in your code, right-click anywhere in the code and select Fix Imports or press Ctrl+Shift+I. In the Fix All Imports dialog box accept the defaults to update the import statements and click OK.

As you can see, you call the FileChooser’s getSelectedFile() method to determine which file the user clicked, so you can work with it. This example reads the file contents and displays them in the TextArea.

Implementing a File Filter

Now you add a custom file filter that makes the File Chooser display only *.txt files.

  1. Switch to the Design mode and select the fileChooser in the Navigator window.

  2. In the Properties window, click the elipsis ("…​") button next to the fileFilter property.

  3. In the File Filter dialog box, select Custom Code from the combobox.

combobox small
  1. Type the following in the text field:

new MyCustomFilter()
  1. Click OK.

  2. To make the custom code work, you write an inner (or outer) class MyCustomFilter that extends the FileFilter class. Copy and paste the following code snippet into the source of your class below the import statements to create an inner class implementing the filter.

    class MyCustomFilter extends javax.swing.filechooser.FileFilter {
        @Override
        public boolean accept(File file) {
            // Allow only directories, or files with ".txt" extension
            return file.isDirectory() || file.getAbsolutePath().endsWith(".txt");
        }
        @Override
        public String getDescription() {
            // This description will be displayed in the dialog,
            // hard-coded = ugly, should be done via I18N
            return "Text documents (*.txt)";
        }
    }
To learn how to implement smarter, switchable file filters, have a look at the addChoosableFileFilter method.

Running the Application

  1. Right-click the JFileChooserDemo project and select Run to start the sample project.

  2. In the Run Project dialog box select the jfilechooserdemo.resources.JFileChooserDemo main class and click OK.

run
  1. In the running Demo application, choose Open in the File menu to trigger the action. The result should look like this:

result jfilechooserdemo small
  1. To close the application, select Exit in the File menu.

Have a look at other useful Swing windows and dialogs like the ColorChooser or the OptionPane in the GUI Palette.

Next Steps