Java Reference
In-Depth Information
current directory and file name. On pressing of the Escape key, text is cleared. Listing 9-14
shows the new
ActionListener
.
Listing 9-14.
ActionListener for JFileChooser in Your JFrame
// Create ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JFileChooser theFileChooser = (JFileChooser)actionEvent.getSource();
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
File selectedFile = theFileChooser.getSelectedFile();
directoryLabel.setText(selectedFile.getParent());
filenameLabel.setText(selectedFile.getName());
} else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
directoryLabel.setText(" ");
filenameLabel.setText(" ");
}
}
};
fileChooser.addActionListener(actionListener);
With the addition of the
ActionListener
, the program is now complete in the sense that
selection is now active. Figure 9-26 shows what this window would look like after selection of
the
COPYRIGHT
file within the
c:\jdk1.5.0
directory.
Figure 9-26.
JFileChooser within a custom window