Java Reference
In-Depth Information
Example 3−4: FileLister.java (continued)
private FilenameFilter filter; // An optional filter for the directory
private String[] files; // The directory contents
private DateFormat dateFormatter = // To display dates and time correctly
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
/**
* Constructor: create the GUI, and list the initial directory.
**/
public FileLister(String directory, FilenameFilter filter) {
super("File Lister");
// Create the window
this.filter = filter;
// Save the filter, if any
// Destroy the window when the user requests it
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { dispose(); }
});
list = new List(12, false); // Set up the list
list.setFont(new Font("MonoSpaced", Font.PLAIN, 14));
list.addActionListener(this);
list.addItemListener(this);
details = new TextField(); // Set up the details area
details.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
details.setEditable(false);
buttons = new Panel(); // Set up the button box
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT, 15, 5));
buttons.setFont(new Font("SansSerif", Font.BOLD, 14));
up = new Button("Up a Directory"); // Set up the two buttons
close = new Button("Close");
up.addActionListener(this);
close.addActionListener(this);
buttons.add(up);
// Add buttons to button box
buttons.add(close);
this.add(list, "Center");
// Add stuff to the window
this.add(details, "North");
this.add(buttons, "South");
this.setSize(500, 350);
listDirectory(directory);
// And now list initial directory.
}
/**
* This method uses the list() method to get all entries in a directory
* and then displays them in the List component.
**/
public void listDirectory(String directory) {
// Convert the string to a File object, and check that the dir exists
File dir = new File(directory);
if (!dir.isDirectory())
throw new IllegalArgumentException("FileLister: no such directory");
// Get the (filtered) directory entries
files = dir.list(filter);
Search WWH ::




Custom Search