O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required