Java Reference
In-Depth Information
You limit the files in the list in the dialog to display only the files you want by calling the
addChoos-
ableFileFilter()
method, with an object of your file filter class as the argument.
You can define your own file filter class for use with the Sketcher program as follows:
import javax.swing.filechooser.FileFilter;
import java.io.File;
public class ExtensionFilter extends FileFilter {
public ExtensionFilter(String ext, String descr) {
extension = ext.toLowerCase();
// Store the extension as lower case
description = descr;
// Store the description
}
public boolean accept(File file) {
return(file.isDirectory() ||
file.getName().toLowerCase().endsWith(extension));
}
public String getDescription() {
return description;
}
private String description;
// Filter description
private String extension;
// File extension
}
Directory "Sketcher 1 saving a sketch to a file"
Add the
ExtensionFilter.java
source file to the Sketcher program directory. The
accept()
method
determines whether or not a file is displayed in a file chooser list. A file is accepted if either of the operands
for the
||
operator in the method evaluates to
true
. The
isDirectory()
method for a
File
object returns
true
if the object represents a directory and not a file. This is the first operand for the
||
operator, so all
directories are displayed in the list by this filter. The second operand is
true
when the extension for a file
path in the
File
object is
extension
. The
getName()
method for a
File
object is the equivalent of the
getFileName()
method for a
Path
object; it returns the name of the file as a
String
object without the root
path. After converting it to lowercase, calling
endsWith()
for the
String
object results in
true
if the string
ends with the argument
extension
, so all files with that extension are included in the list.
To identify a filter for files with the extension
.ske,
you could add a field to the
SketcherFrame
class:
private ExtensionFilter sketchFilter = new ExtensionFilter(
".ske", "Sketch files (*.ske)");
Directory "Sketcher 1 saving a sketch to a file"