Adding a File Chooser to a Java Application
| This tutorial needs a review. You can 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.
You can download the resulting project with a file chooser.
To complete this tutorial, you need the following software and resources.
| Software or Resource | Version Required |
|---|---|
Version 7.0 or more recent |
|
Java Development Kit (JDK) |
Version 6, 7, or 8 |
Creating the Application Form
In this section, you create a JFrame container and add a few components to it.
To create the JFrame form:
-
Right-click the Source Packages node and choose New > Other. Choose the Swing GUI Forms category and the JFrameForm file type. Click Next.
-
For Class Name, type
JFileChooserDemo. -
For Package, type
jfilechooserdemo.resources.
-
Click Finish.
-
In the Properties window, enter
Demo applicationfor the Title property and press Enter to confirm.
To add components to the JFrame form:
-
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.
-
Right-click the Edit item of the Menu Bar component and select Delete in the context menu.
-
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.
*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.
-
Right-click the jMenuItem1 in the Design view and choose Change Variable Name from the context menu. Rename the item to
Openand click OK. -
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
Openand press Enter to confirm. -
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:
-
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
JMenuItem1is going to be placed.
-
Right-click
jMenuItem1in the Design view and choose Change Variable Name from the context menu. Rename the item toExitand click OK. -
Make sure that the
jMenuItem1is still selected in the Design view. Press the Space bar to edit the text of the component. Change the text toExitand press Enter to confirm. -
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().TheExitActionPerformednode appears in the Navigator window below theOpenActionPerformed()node. -
To make the Exit menu item work, you include the following source into the
ExitActionPerformed()method body:
System.exit(0);
-
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.
-
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:
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
-
Choose Window > Navigating > Navigator to open the Navigator window, if it is not open yet.
-
In the Navigator, right-click the
Other Componentsnode. 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.
-
A look in the Navigator confirms that a
JFileChooserwas added to the form. -
Right-click the
JFileChoosernode and rename the variable tofileChooser.
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
-
Click to select the
JFileChooserin the Navigator window, and then edit its properties in the Properties dialog box. Change thedialogTitleproperty toThis is my open dialog, press Enter and close the Properties dialog box. -
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.
-
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.
-
Switch to the Design mode and select the
fileChooserin the Navigator window. -
In the Properties window, click the elipsis ("…") button next to the
fileFilterproperty. -
In the File Filter dialog box, select Custom Code from the combobox.
-
Type the following in the text field:
new MyCustomFilter()
-
Click OK.
-
To make the custom code work, you write an inner (or outer) class
MyCustomFilterthat extends theFileFilterclass. 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
-
Right-click the JFileChooserDemo project and select Run to start the sample project.
-
In the Run Project dialog box select the
jfilechooserdemo.resources.JFileChooserDemomain class and click OK.
-
In the running Demo application, choose Open in the File menu to trigger the action. The result should look like this:
-
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
-
Implementing Java GUIs in Developing Applications with NetBeans IDE
-
Binding Beans and Data in a Java Application with NetBeans IDE








