WebNFS Developer's Guide

Determining Which File Chooser to Bring Up

The DemoEditor program had separate menu items for opening and saving a file, so that a different file chooser would appear, depending on the item selected. (Remember, however, that the same XFileChooser object is instantiated in both cases.) Things are different with the XFileChooserDemo program: There's a single button, Show File Chooser, and which dialogue this button brings up depends on which radio button (Open, Save, or Custom) in the main window has been selected. The code for using the Open button is shown below.


// Create an `Open' radio button
openButton = new JRadioButton("Open")
...
openButton.addActionListener(optionListener);
// Create `Show File Chooser' button
button = new JButton("Show File Chooser");
button.addActionListener(this);

When a radio button is selected, OptionListener() is called. If the Open radio button is selected, the OptionListener() sets the file chooser to be an Open file chooser with the setDialogType() method:


class OptionListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     JComponent c = (JComponent) e.getSource();
     if (c == openButton) {
        chooser.setDialogType(XFileChooser.OPEN_DIALOG);
...

OptionListener() does the same sort of thing when Save is chosen, except that the dialogue type is set to SAVE_DIALOG. Note, by the way, that setDialogType() and the OPEN_DIALOG field are inherited from JFileChooser.

In the DemoEditor program, the actionPerformed() method chose between bringing up a file chooser with showOpenDialog() or showSaveDialog(), depending on whether Open or Save was selected off the File menu. Since the dialog type is already set here, it is not necessary to differentiate between them in actionPerformed(). Instead, a "generic" method, showDialog(), is used to bring up the file chooser:


public void actionPerformed(ActionEvent e) {
   int retval = chooser.showDialog(frame, null);
...

Another difference to note is that the XFileChooser is not instantiated in actionPerformed(), as it was in the DemoEditor program. Instead, it's instantiated at the class level so that the dialog type can be set in OptionListener(). In both programs, however, a single file chooser is instantiated for all operations (Open, Save, or custom).