You are on page 1of 7

Search: Choose page language Brazilian Portuguese Japanese HOME / Docs & Support Russian Simplified Chinese

Adding a File Chooser to a Java Application


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. Contents

Creating the Application Creating the Application Form Adding the File Chooser Configuring the File Chooser Running the Application To complete this tutorial, you need the following software and resources. Software or Resource NetBeans IDE Version Required Version 6.9 or 7.0

Java Development Kit (JDK) Version 6

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. 4. Make sure that the Set As Main Project checkbox is selected.

5. 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.

4. Click Finish. 5. 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 in the main menu or click Ctrl+Shift+8 to open it.

2. Right-click the Edit item of the Menu Bar component and select Delete in the context menu. 3. 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.

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

click OK. 5. 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. 6. 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:

Training
Java Programming Language

Support
Oracle Development Tools Support Offering for NetBeans IDE

Documentation
General Java Development External Tools and Services Java GUI Applications Java EE & Java Web Development Web Services Applications NetBeans Platform (RCP) and Module Development PHP Applications C/C++ Applications Mobile Applications Sample Applications Demos and Screencasts

7. 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.

More
FAQs 8. Right-click jMenuItem1 in the Design view and choose Change Variable Name from the context menu. Rename the item to Exit and Contribute Documentation! click OK. 9. 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 Docs for Earlier Releases to Exit and press Enter to confirm. 10. 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. 11. To make the Exit menu item work, you include the following source into the ExitActionPerformed() method body:
System.exit(0);

12. 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.

13. 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


1. Choose Window > Navigating > Inspector to open the Inspector window, if it is not open yet. 2. In the Inspector, right-click the JFrame node. Choose Add From Palette > Swing Windows > File Chooser from the context menu GUI Builder Tip: 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. 3. A look in the Inspector confirms that a JFileChooser was added to the form. 4. Right-click the JFileChooser node and rename the variable to fileChooser.

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 Inspector window, and then edit its properties in the Properties dialog box. Change the 'dialogTitle'

1. Click to select the JFileChooser in the Inspector 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. 3. 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 Inspector window. 2. In the Properties window, click the elipsis ("...") button next to the File Filter property. 3. In the File Filter dialog box, select Custom Code from the combobox.

4. Type new MyCustomFilter() in the text field. Click OK. 5. 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)"; } }

Note: To learn how to implement smarter, switchable file filters, have a look at the addChoosableFileFilter method.

Running the Application

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. 3. In the running Demo Application, choose Open in the File menu to trigger the action. The result should look like this:

4. 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. Send Us Your Feedback

Next Steps
Binding Beans and Data in a Desktop Application with NetBeans IDE Internationalizing a GUI Form with NetBeans IDE Java Tutorial: How to use File Choosers

SiteMap About Us Contact Legal By use of this website, you agree to the NetBeans Policies and Terms of Use. 2011, Oracle Corporation and/or its affiliates. Companion Projects: Sponsored by

You might also like