Chapter 18. File Dialogs and Choosers

Filenames are problematic, even if you don’t have to worry about cross-platform idiosyncrasies. Users forget filenames, mistype them, can’t remember the exact path to files they need, and more. The proper way to ask a user to select a file is to show them a list of the files in the current directory and ask them to select from that list. You also need to allow them to navigate between directories, insert and remove disks, mount network servers, and more.

Most graphical user interfaces provide standard widgets for selecting a file. In Java the platform’s native file selector widget is exposed through the java.awt.FileDialog class. Like many native peer-based classes, however, FileDialog doesn’t behave exactly the same on all platforms. Therefore, Swing provides a pure Java implementation of a file dialog, the javax.swing.JFileChooser class. JFileChooser has much more reliable though less native cross-platform behavior.

File Dialogs

File dialogs are the standard open and save dialogs provided by the host GUI. Users use them to pick a directory and a name under which to save a file or to choose a file to open. The appearance varies from platform to platform, but the intent is the same. Figure 18-1 shows a standard Save dialog on the Mac; Figure 18-2 shows a standard open dialog on Linux.

The Mac’s standard Save dialog
Figure 18-1. The Mac’s standard Save dialog
Figure 18-2. Gnome ...

Get Java I/O, 2nd Edition 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.