Adding a File Chooser to a Java Application
Contributed by Petr Dvorak (Dec 2009), maintained by Ruth Kusterer
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 desktop application
that loads a .txt file into a Text Area.
You can download the resulting project with file chooser.
Contents
Requirements
To complete this tutorial, you need the following software and resources:
Creating a Desktop Application
First you create a new Java Desktop Application:
- From the main menu, choose File>New Project. Choose the Java category
and the Java Desktop Application project type. Click Next.
- Fill in the Project Name, for example "JFileChooserDemo".
- Under Application Shell, make sure "Basic Application" is selected.
- Leave the rest as is, and click Finish.
The New Project wizard creates a new basic Java Desktop application
and opens it in the Projects window. Double-click the Sources Packages node
and have a look at the three source files that were generated:
JFileChooserDemoApp.java, JFileChooserDemoView.java,
and JFileChooserDemoAboutBox.java.

The Basic Desktop Application template contains three files
Adding a Menu Item and Toolbar
Double-click the JFileChooserDemoView.java file to open it in the editor.
Make sure that the file is opened in the design mode of the GUI builder as shown below.

The JFileChooserDemoView.java file in the NetBeans GUI builder
Choose Windows>Palette to open the Component Palette. Alternatively, you can press the Ctrl+Shift+8 keyboard shortcut.
Open the Swing Menus category from the Palette. Drag a new Menu Item (JMenuItem) and drop it into the File menu in the Designer.
Right-click jMenuItem1 in the Designer and choose Change Variable Name from the context menu. Rename the item to openFileMenuItem.
Make sure that the openFileMenuItem is still selected in the Designer. Press the Space bar to edit the text of the component. Change the text to "Open text file".
Next, you specify the action handler for the Open menu item. Right-click the menu item and choose Events>Action>Action Performed from the context menu. A new event handler method is generated which is named openFileMenuItemActionPerformed(). Copy the event handler's method name into the clipboard, you will need it later.

Changing a menu item's variable name
Switch back into Design mode. Open the Swing Containers category from the Palette. Drag a Tool Bar (JToolBar) anywhere into the designer.
Open the Swing Controls category from the Palette. Drag one Button (JButton) and drop it into the tool bar area.
Click to select the button, and press the Space bar. Change the button's text to "Open".
Right-click the tool bar in the Designer and choose Change Variable Name from the context menu. Rename the tool bar to 'toolbar'.
Right-click the button in the Designer and choose Change Variable Name from the context menu. Rename the button to 'openToolbarItem'.
Earlier you created an event handler for the "Open" menu item, openFileMenuItemActionPerformed.
You want the Open button to trigger the same event handler as the Open menu item:
Click the button to select it, then choose the Events tab in the Properties window.
Paste the name of the method (openFileMenuItemActionPerformed) from the clipboard
into the "actionPerformed" event, and press Enter to confirm.
From the Swing Controls category of the Palette, drag a Text Area (JTextArea) into the form. Rename the variable to 'textarea'. The form should look like the following screenshot:

Desktop application with an Open action in the toolbar and menu
You have set up a simple desktop application as a base for this tutorial.
Next you add the actual File Chooser.
Adding the File Chooser
Choose Window>Navigating>Inspector to open the Inspector window, if it is not open yet.
In the Inspector, right-click the 'Form JFileChooserDemoView' node.
Choose Add From Palette>Swing Windows>File Chooser from the context menu.

Adding a FileChooser component using the inspector view
A look in the Inspector confirms that a JFileChooser was added to the form.
GUI Designer Tip:
As an alternative to the 'Add From Palette' context-menu,
you can also drag&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.
Right-click the JFileChooser node and rename the variable to "fileChooser".
Inspector Tip:
If you don't have a Java Desktop Application, or if you just have any
JFrame form, right-click the "Other components" node instead of
the "Form JFileChooserDemoView" node. This way you can add a JFileChooser
component to the JFrame (to the JFrame class)
even if it is not a visible container.

The Inspector contains an Other Components node for Swing components such as JFrame forms
Configuring the File Chooser
Implementing the Open Action
Click to select the JFileChooser in the Inspector window,
and then edit its properties in the Properties window.
Change the 'dialogTitle' property to "This is my open dialog".
Click to Source button in the editor to switch to Source mode.
To integrate the file chooser into your application,
paste the following code snippet into the existing
openFileMenuItemActionPerformed() method.
private void openFileMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this.getFrame());
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.");
}
}
If the editor reports errors in your code,
press Ctrl+Shift+I to update the import statements.
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 to the File Chooser.
Select the FileChooser in the Inspector window.
In the Properties window, click the elipsis ("...") button
next to the File Filter property.
In the File Filter dialog, select Custom Code from the combobox.
Type new MyCustomFilter() in the text field.
Click OK to confirm the dialog.
To make the custom code work, you must 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 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
Click the Run button to start the sample project. In the Java Application,
either click the Open button or the choose the Open menu to trigger the action.
The result should look like this:

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