A quick JFileChooser demo

Today, I noticed that many new NetBeans users have a difficulty of implementing a file chooser functionality. Usually, you just write all the code by hand, but there is also a way how to achieve several goals using the designer in the NetBeans IDE.

This tutorial should demonstrate how to leverage the NetBeans GUI Builder for implementing a custom file chooser. As a setup, we will also create a small Java desktop application.

You can download the resulting project with file chooser.

Prerequisites

Before you start, make sure you have NetBeans IDE 6.8 and JDK 1.6.

Step-by-step guide

As a first thing, we create a new Java Desktop Application:

  1. Invoke File>New Project, select Java category and choose Java Desktop Application project type
  2. Click Next, fill in some application name ("JFileChooserDemo") and make sure Basic Application is selected
  3. Click Finish

At this moment, a new Java Desktop application with three important files is created:

  • JFileChooserDemoApp
  • JFileChooserDemoView
  • JFileChooserDemoAboutBox

 Just as on this picture:


Projects view

 Double-click the JFileChooserDemoView to make sure it is opened in the designer.


Java Desktop Application - GUI Builder

Open the component palette (Ctrl+Shift+8).

Drag a new Menu Item (JMenuItem, from Swing Menus category) in the menu bar that was created by default.

Right-click this item in the designer and invoke Change Variable Name - rename the item to openFileMenuItem. Then, press Space (to start editing the text of the component that is selected in the designer) and change the text to "Open text file".

To set an action to this menu item, right click it and invoke Events>Action>Action Performed. A new method is generated, it is called for example openFileMenuItemActionPerformed - copy the name to the clipboard for a while.


Changing menu item variable name

Drag a Tool Bar (from Swing Containers category) to the designer and add one button (JButton, from Swing Controls) to the tool bar.

Change the button's text to "Open" by selecting it and pressing Space.

Rename both components' variable names again using the context menu, so that you don't have to stick with the ugly "jButton1"-like names.

Currently, you have an event handler for the "Open" menu item. To set the same event handler to the button, single-click the button and select Events tab in the Properties view. Paste the name of the method in the "actionPerformed" event and press Enter to confirm.

At this moment, the method "openFileMenuItemActionPerformed" (or similar name) is set as an event handler for both button in the toolbar and menu item.

Finally, add a JTextArea (Swing Controls) in the form (and rename the variable). The form should look like this:


Java Desktop Application - GUI Builder

So, now we have finished the basics. Let's add a JFileChooser to the form.

Open the inspector window if it is not opened (Window>Navigating>Inspector) and right-click Form JFileChooserDemoView node.

Invoke "Add From Palette>Swing Windows>File Chooser".

A JFileChooser is added in the inspector. Right-click the node and rename the variable to "fileChooser".


Add JFileChooser using the inspector view

Note: You can also drag&drop the File Chooser from the palette to the white area of the GUI Builder - it will have the same result. It is a bit harder, though, because the default preview of the JFileChooser is rather big and you might end up with the window being inserted inside some of the panels, which is not what you want.

Note: If you don't create a Java Desktop Application or if you just have a JFrame form, you can right-click the "Other components" node instead of the "Form JFileChooserDemoView" node - it will add the JFileChooser component to the JFrame (to the JFrame class) but not in its visual part...


Inspector contains Other Components node for the default JFrame forms

Now, you can click the JFileChooser in the inspector and edit some of its properties in the Properties view. For example, you can edit the title of the dialog by editing the dialogTitle property (change it to "This is open dialog").

To display the file chooser from your application, just paste this code to the openFileMenuItemActionPerformed method and press Ctrl+Shift+I to fix the imports (otherwise, there will be some errors in your code):

    int returnVal = fileChooser.showOpenDialog(this.getFrame());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        // ... code that loads the contents of the file in the text area
    } else {
        // ...
    }

Let's do some minor work to add some custom filter.

Note: Users who used to work with MS Visual Studio and .NET might be familiar with a quick but ugly way of making custom filters - typing extensions and descriptions of the filter with a vertical separator in a special property, like this:

openFileDialog.Filter = "Bitmap images|\*.bmp|All files|\*.\*";

see - http://msdn.microsoft.com/en-us/magazine/cc300434.aspx#S1. Java does it in a more difficult but cleaner way...

Select the File Chooser in the Inspector window. Click the asterisk ("...") button by the File Filter property in the properties view.

Select Custom code from the combobox in the dialog that shows up and type "new MyCustomFilter()" in the text field and confirm the dialog - yes, the code will not be compilable now, we will fix it.

All we need to do is to write an inner (or outer, if you like) class that extends the FileFilter class. Just copy and paste following code in the source of your class to create an inner class.

    class MyCustomFilter extends javax.swing.filechooser.FileFilter {

        @Override
        public boolean accept(File file) {
            // Allow just directories and 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)";
        }

    }

OK, so that should be it. If there is still something unclear, do not hesitate to ask in the discussion below. If you start the sample project, the result should look something like this:


JFileChooser demo - result

If you want to have more switchable file filters, see addChoosableFileFilter method. You can indeed implement all the stuff yourself, following the tutorial on How to use File Choosers.

Comments:

A good tutorial Petr. I like the way you covered all the bases here, including how to fix your imports. You might want to grammar check it, because I noticed the word 'tough' where you obviously meant to have 'though'. A spell check allows that, but a grammar check would have caught it. I only skimmed it, so there might be a couple of more such typos.

Posted by Mike Riley on December 19, 2009 at 02:01 AM PST #

Hi Mike! Thanks for the catch... I fixed the one you mentioned plus several more...

I think that when I am bored too much, I should go through all my blog posts and check the grammar, because the only thing I use for text correction is the firefox spellcheck (we edit the Sun blogs in relatively small javascript wysiwyg editor). I can imagine that reading texts in Czenglish (English enhanced by a bit of a Czech language - no/extra articles, wrong word order, etc.) can be refreshing. :)

Posted by Petr Dvorak on December 19, 2009 at 06:24 AM PST #

Awesome tutorial! Thanks.

Posted by Alton on December 02, 2010 at 10:38 AM PST #

hey pter thanks for this code...i am using the same fileChooser.showOpenDialog() method, but instead of this.getFrame(), my Summarizer.this as an arguement isnt working...Summarizer is my project name...is it correct? it literally freezes my application..it doesnt show any error / exception..only an error sound..i cant even close my application, have to close it via the task manager...

i would be really thankful to u, if u help..thanks

Posted by navin israni on March 17, 2011 at 04:18 PM PDT #

Post a Comment:
Comments are closed for this entry.
Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today