// 
//     Licensed to the Apache Software Foundation (ASF) under one
//     or more contributor license agreements.  See the NOTICE file
//     distributed with this work for additional information
//     regarding copyright ownership.  The ASF licenses this file
//     to you under the Apache License, Version 2.0 (the
//     "License"); you may not use this file except in compliance
//     with the License.  You may obtain a copy of the License at
// 
//       http://www.apache.org/licenses/LICENSE-2.0
// 
//     Unless required by applicable law or agreed to in writing,
//     software distributed under the License is distributed on an
//     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//     KIND, either express or implied.  See the License for the
//     specific language governing permissions and limitations
//     under the License.
//

= Adding a File Chooser to a Java Application
:jbake-type: tutorial
:jbake-tags: tutorials 
:jbake-status: published
:syntax: true
:icons: font
:source-highlighter: pygments
:toc: left
:toc-title:
:description: Adding a File Chooser to a Java Application - Apache NetBeans
:keywords: Apache NetBeans, Tutorials, Adding a File Chooser to a Java Application

_Contributed by Petr Dvorak link:http://blogs.oracle.com/joshis/entry/a_quick_jfilechooser_demo[+(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 link:https://netbeans.org/projects/samples/downloads/download/Samples%252FJava%252FJFileChooserDemo.zip[+the resulting project with a file chooser+]. 


image::images/netbeans-stamp-80-74-73.png[title="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 

|link:http://netbeans.org/downloads/[+NetBeans IDE+] |Version 7.0 or more recent 

|link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+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.

[.feature]
--
image::images/newproj-small.png[role="left", link="images/newproj.png"]
--


[start=4]
. 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`.

[.feature]
--
image::images/newjframeform-small.png[role="left", link="images/newjframeform.png"]
--


[start=4]
. Click Finish.

[start=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 from the main menu.

[.feature]
--
image::images/menubaradded-small.png[role="left", link="images/menubaradded.png"]
--


[start=2]
. Right-click the Edit item of the Menu Bar component and select Delete in the context menu.

[start=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.

[.feature]
--
image::images/menuitemadded-small.png[role="left", link="images/menuitemadded.png"]
--

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


[start=4]
. 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.

[start=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.

[start=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:

image::images/openactionperformednavigator.png[]


[start=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.

[.feature]
--
image::images/highlighting-small.png[role="left", link="images/highlighting.png"]
--


[start=8]
. Right-click  ``jMenuItem1``  in the Design view and choose Change Variable Name from the context menu. Rename the item to `Exit` and click OK.

[start=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 to  ``Exit``  and press Enter to confirm.

[start=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.

[start=11]
. To make the Exit menu item work, you include the following source into the `ExitActionPerformed()` method body:

[source,java]
----

			 System.exit(0); 
----

[start=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.

[.feature]
--
image::images/textareadded-small.png[role="left", link="images/textareadded.png"]
--


[start=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:

[.feature]
--
image::images/jfilechooserdemoview_final-small.png[role="left", link="images/jfilechooserdemoview_final.png"]
--

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.


[start=3]
. A look in the Navigator confirms that a  ``JFileChooser``  was added to the form.

[start=4]
. Right-click the  ``JFileChooser``  node and rename the variable to `fileChooser`.

image::images/navigator_jframe.png[]

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.

[source,java]
----

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.


[start=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 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.

[.feature]
--
image::images/combobox-small.png[role="left", link="images/combobox.png"]
--


[start=4]
. Type the following in the text field:

[source,java]
----

new MyCustomFilter()
----

[start=5]
. Click OK.

[start=6]
. 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.

[source,java]
----

    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 link:http://java.sun.com/javase/7/docs/api/javax/swing/JFileChooser.html#addChoosableFileFilter%28javax.swing.filechooser.FileFilter%29[+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.

image::images/run.png[]


[start=3]
. In the running Demo application, choose Open in the File menu to trigger the action. The result should look like this:

[.feature]
--
image::images/result_jfilechooserdemo-small.png[role="left", link="images/result_jfilechooserdemo.png"]
--


[start=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.

link:/about/contact_form.html?to=3&subject=Feedback:%20Adding%20a%20FileChooser[+Send Feedback on This Tutorial+]



== Next Steps

* link:http://www.oracle.com/pls/topic/lookup?ctx=nb8000&id=NBDAG920[+Implementing Java GUIs+] in _Developing Applications with NetBeans IDE_
* link:gui-binding.html[+Binding Beans and Data in a Java Application with NetBeans IDE+]
* link:gui-automatic-i18n.html[+Internationalizing a GUI Form with NetBeans IDE+]
* link:http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html[+Java Tutorial: How to use File Choosers+]
