Java Reference
In-Depth Information
Example 3−3: FileViewer.java (continued)
directory = f.getDirectory(); // Remember new default directory
setFile(directory, f.getFile()); // Load and display selection
f.dispose();
// Get rid of the dialog box
}
else if (cmd.equals("close"))
// If user clicked "Close" button
this.dispose();
//
then close the window
}
/**
* The FileViewer can be used by other classes, or it can be
* used standalone with this main() method.
**/
static public void main(String[] args) throws IOException {
// Create a FileViewer object
Frame f = new FileViewer((args.length == 1)?args[0]:null);
// Arrange to exit when the FileViewer window closes
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) { System.exit(0); }
});
// And pop the window up
f.show();
}
}
Listing Directory and File Information
Just as the
FileViewer
class of Example 3-3 displays the contents of a file in a
TextArea
component, the
FileLister
class, shown in Example 3-4, displays the
contents of a directory in a
java.awt.List
component. When you select a file or
directory name from the list, the program displays information (size, modification
date, etc.) about the file or directory in a
TextField
component. When you dou-
ble-click on a directory, the contents of that directory are displayed. When you
double-click on a file, it displays the contents of the file in a
FileViewer
object.
Figure 3-2 shows a
FileLister
window. Again, if you are not already familiar with
GUI programming in Java, don't expect to understand all of the code until you've
read Chapter 10; instead, just pay attention to the various uses of the
File
object
that are demonstrated in this example.
The GUI mechanics of making the
FileLister
work form a large part of this
example. The
listDirectory()
method lists the contents of a directory, using an
optionally specified
FilenameFilter
object passed to the
FileLister()
construc-
tor. This object defines an
accept()
method that is called for every entry in a
directory to determine whether it should be listed.
The
itemStateChanged()
method is invoked when an item in the list is selected. It
obtains information about the file or directory and displays it. The
actionPer-
formed()
method is another event listener method. This one is invoked when the
user clicks either of the
Button
objects or double-clicks on an item in the list. If
the user double-clicks on a directory, the program lists the contents of that direc-
tory. If the user double-clicks on a file, however, it creates and display a
File-
Viewer
window to list the contents of the file.