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

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.