Java Reference
In-Depth Information
Showing a JFileChooser within a Pop-Up Window
Instead of placing a JFileChooser panel within your own window, you will more typically place
it in a modal JDialog . There are three ways to do this, depending on the text you want to appear
on the approval button:
public int showDialog(Component parentComponent, String approvalButtonText)
public int showOpenDialog(Component parentComponent)
public int showSaveDialog(Component parentComponent)
Calling one of these methods will place the configured JFileChooser into a modal JDialog
and show the dialog box centered over the parent component. Providing a null parent component
centers the pop-up window on the screen. The call doesn't return until the user selects the
approval or cancel button. After selection of one of the two buttons, the call returns a status
value, depending on which button was selected. This status would be one of three JFileChooser
constants: APPROVE_OPTION , CANCEL_OPTION , or ERROR_OPTION .
Caution If the user clicks the approval button without selecting anything, CANCEL_OPTION is returned.
To perform the same task as the previous example, in which an ActionListener was
attached to the JFileChooser (Listing 9-14), you can just show the dialog box and change the
labels based on the return status, instead of relying on the action command, as follows:
JFileChooser fileChooser = new JFileChooser(".");
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
directoryLabel.setText(selectedFile.getParent());
filenameLabel.setText(selectedFile.getName());
} else if (status == JFileChooser.CANCEL_OPTION) {
directoryLabel.setText(" ");
filenameLabel.setText(" ");
}
With this technique, the file chooser will be shown in another window, instead
of within the window with the two labels. Notice that this version switches from checking
the String return values of the earlier example to checking int return values:
[if (command.equals(JFileChooser.APPROVE_SELECTION)) versus if (status ==
JFileChooser.APPROVE_OPTION) ].
JFileChooser Properties
Once you understand the basic JFileChooser usage, you can customize the component's
behavior and appearance by modifying its many properties. Table 9-10 shows the 26 properties
of JFileChooser .
 
Search WWH ::




Custom Search