Java Reference
In-Depth Information
Example 3−4: FileLister.java (continued)
// Sort the list of filenames. Prior to Java 1.2, you could use
// com.davidflanagan.examples.classes.Sorter.sort() to sort instead.
java.util.Arrays.sort(files);
// Remove any old entries in the list, and add the new ones
list.removeAll();
list.add("[Up to Parent Directory]"); // A special case entry
for(int i = 0; i < files.length; i++) list.add(files[i]);
// Display directory name in window titlebar and in the details box
this.setTitle(directory);
details.setText(directory);
// Remember this directory for later.
currentDir = dir;
}
/**
* This ItemListener method uses various File methods to obtain information
* about a file or directory. Then it displays that info.
**/
public void itemStateChanged(ItemEvent e) {
int i = list.getSelectedIndex() - 1; // minus 1 for Up To Parent entry
if (i < 0) return;
String filename = files[i]; // Get the selected entry
File f = new File(currentDir, filename); // Convert to a File
if (!f.exists()) // Confirm that it exists
throw new IllegalArgumentException("FileLister: " +
"no such file or directory");
// Get the details about the file or directory, concatenate to a string
String info = filename;
if (f.isDirectory()) info += File.separator;
info += " " + f.length() + " bytes ";
info += dateFormatter.format(new java.util.Date(f.lastModified()));
if (f.canRead()) info += " Read";
if (f.canWrite()) info += " Write";
// And display the details string
details.setText(info);
}
/**
* This ActionListener method is invoked when the user double-clicks on an
* entry or clicks on one of the buttons. If they double-click on a file,
* create a FileViewer to display that file. If they double-click on a
* directory, call the listDirectory() method to display that directory
**/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close) this.dispose();
else if (e.getSource() == up) { up(); }
else if (e.getSource() == list) { // Double click on an item
int i = list.getSelectedIndex(); // Check which item
if (i == 0) up();
// Handle first Up To Parent item
else {
// Otherwise, get filename
String name = files[i-1];
File f = new File(currentDir, name);
// Convert to a File
String fullname = f.getAbsolutePath();
Search WWH ::




Custom Search