Recipe 14.11 Choosing a File with JFileChooser


Problem

You want to allow the user to select a file by name using a traditional windowed file dialog.

Solution

Use a JFileChooser.

Discussion

The JFileChooser dialog provides a fairly standard file chooser. It has elements of both a Windows chooser and a Mac chooser, with more resemblance to the former than the latter. If you want to have control over which files appear, you need to provide one or more FileFilter subclasses. Each FileFilter subclass instance passed into the JFileChooser 's addChoosableFileFilter( ) method becomes a selection in the chooser's Files of Type: choice. The default is All Files (*.*). Figure 14-10 shows my demo program in action.

Figure 14-10. JFileChooserDemo in action
figs/jcb2_1410.gif


Let's look at the code for using JFileChooser :

import com.darwinsys.util.*; import javax.swing.*; import java.awt.event.*; import java.io.*; import java.util.*; /** A simple demo of a JFileChooser in action. */ public class JFileChooserDemo extends JPanel {     /** Constructor */     public JFileChooserDemo(JFrame f) {         final JFrame frame = f;         final JFileChooser chooser = new JFileChooser( );         JFileFilter filter = new JFileFilter( );         filter.addType("java");         filter.addType("class");         filter.addType("jar");         filter.setDescription("Java-related files");         chooser.addChoosableFileFilter(filter);         JButton b = new JButton("Choose file...");         add(b);         b.addActionListener(new ActionListener( ) {             public void actionPerformed(ActionEvent e) {             int returnVal = chooser.showOpenDialog(frame);             if (returnVal == JFileChooser.APPROVE_OPTION) {                 System.out.println("You chose a file named: " +                      chooser.getSelectedFile( ).getPath( ));             } else {                 System.out.println("You did not choose a file.");             }             }         });     }     public static void main(String[] args) {         JFrame f = new JFrame("JFileChooser Demo");         f.getContentPane( ).add(new JFileChooserDemo(f));         f.pack( );         f.setVisible(true);         f.addWindowListener(new WindowCloser(f, true));     } }

In this example, I set up a FileFilter for Java files. Note that FileFilter exists both in javax.swing.filechooser and java.io (an older version, not for use here; see Recipe 11.7). The javax.swing.filechooser.FileFilter interface has only two methods: boolean accept(File) and String getDescription( ). This is enough for a totally fixed-function file filter: you could hardcode the list of extensions that should be accepted, for example. The following class is similar in spirit to the ExampleFileFilter included in the JDK demo directory; Sun claims that its version will be moved into javax.swing.filechooser in a subsequent release of Swing.

/** A simple FileFilter class that works by filename extension,  * like the one in the JDK demo called ExampleFileFilter, which  * has been announced to be supported in a future Swing release.  */ class JFileFilter extends javax.swing.filechooser.FileFilter {     protected String description;     protected ArrayList exts = new ArrayList( );     public void addType(String s) {         exts.add(s);     }     /** Return true if the given file is accepted by this filter. */     public boolean accept(File f) {         // Little trick: if you don't do this, only directory names         // ending in one of the extensions appear in the window.         if (f.isDirectory( )) {             return true;         } else if (f.isFile( )) {             Iterator it = exts.iterator( );             while (it.hasNext( )) {                 if (f.getName( ).endsWith((String)it.next( )))                     return true;             }         }         // A file that didn't match, or a weirdo (e.g., Unix device file?).         return false;     }     /** Set the printable description of this filter. */     public void setDescription(String s) {         description = s;     }     /** Return the printable description of this filter. */     public String getDescription( ) {         return description;     } }



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net