Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata