The JFileChooser Class

Since it plays such an integral role in just about every commercial application, let’s look at the file chooser first. The JFileChooser class bundles a directory pane and typical selection buttons into a handy interface. Figure 12-2 shows the dialog window you get when you select the Save option of a simple application. As you might expect, other L&Fs can also be applied to this chooser.

The JFileChooser save dialog (Metal L&F)

Figure 12-2. The JFileChooser save dialog (Metal L&F)

Figure 12-3 shows sample file choosers for open and save dialogs in the Windows, Motif, and Mac OS X L&Fs.

JFileChooser in the Metal, Motif, and Mac L&Fs

Figure 12-3. JFileChooser in the Metal, Motif, and Mac L&Fs

The application itself reports only which file (or files, if you use the Open option) you chose to open or save. Our application has a Pick Directory button that restricts the chooser to directories. The event handlers for each button do most of the interesting work. In each case, we create a new JFileChooser object, make any changes to the default properties that we need for the particular action, and then show the dialog. As you will see from the constants discussed later, the int returned from the showDialog( ) method indicates whether the user accepted a file selection or canceled the dialog. If we have a successful selection, our example application puts the ...

Get Java Swing, 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.