23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 13. File Dialogs and Choosers<br />

<strong>Java</strong> I/O<br />

Filenames are problematic, even if you don't have to worry about cross-platform<br />

idiosyncrasies. Users forget filenames, mistype them, can't remember the exact path to files<br />

they need, and more. The proper way to ask a user to select a file is to show them a list of the<br />

files in the current directory and get them to select from that list. You also need to allow them<br />

to navigate between directories, insert and remove floppy disks, mount network servers, and<br />

more.<br />

Most graphical user interfaces (and not a few nongraphical ones) provide standard widgets for<br />

selecting a file. In <strong>Java</strong> the platform's native file selector widget is exposed through the<br />

java.awt.FileDialog class. Like many native peer-based classes, however, FileDialog<br />

doesn't behave exactly the same on all platforms. Therefore, Swing (part of the <strong>Java</strong><br />

Foundation Classes) provides a pure <strong>Java</strong> implementation of a file dialog, the<br />

javax.swing.JFileChooser class. [1] JFileChooser (and Swing in general) has much more<br />

reliable cross-platform behavior.<br />

13.1 File Dialogs<br />

I'm going to jump out of the java.io package for a minute to pick up one file-related class<br />

from the AWT, java.awt.FileDialog. File dialogs are the standard open and save dialogs<br />

provided by the host GUI. Users use them to pick a directory and a name under which to save<br />

a file or to choose a file to open. The appearance varies from platform to platform, but the<br />

intent is the same. Figure 13.1 shows a standard Save dialog on the Mac; Figure 13.2 shows a<br />

standard open dialog on Solaris.<br />

Figure 13.1. The Mac's standard Save dialog<br />

1 The package name for Swing has changed several times since its first early access release. javax.swing is its final home—this package<br />

name is used in Swing 1.1 (for use with JDK 1.1) and <strong>Java</strong> 2 (which includes Swing and the rest of JFC). For more information about Swing, see <strong>Java</strong><br />

Swing, by Robert Eckstein, Marc Loy, and Dave Wood (O'Reilly & Associates, 1998).<br />

306

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!