O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 an MS-Windows chooser and a Mac chooser, with more resemblance to the former than the latter. If you want to have control over what 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 13-8 shows my demo program in action.

JFileChooserDemo in action

Figure 13-8. JFileChooserDemo in action

Let’s look at the code for using the 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required