Java Reference
In-Depth Information
All the buttons in the dialog are fully operational. Go ahead and try them out, and then save the sketch
using the default name. Next time you save the sketch the dialog won't appear. Be sure to check out the
button tooltips. You should see the shortcut key combination as well as our tooltip text.
If you create a few sketch files, you should also get a warning if you attempt to overwrite an existing
sketch file with a new one.
You can now save any sketch in a file - regardless of its complexity - with protection against accidentally
overwriting existing files. I hope you agree that the save operation was remarkably easy to implement.
How It Works
This just calls our saveOperation() method in the SketchFrame object associated with the
FileAction object containing the actionPerformed() method. This carries out the save as we
have discussed.
Creating a File Filter
One customizing option we haven't used but you might like to try is to supply a file filter for our sketch
files. The default filter in a JFileChooser object accepts any file or directory, but you can add filters
of your own, and these implements two abstract methods declared in the FileFilter class:
Method
Description
accept(File file)
Returns true if the file represented by the object file is
accepted by the file filter, and false otherwise.
getDescription()
Returns a String object describing the filter - for example,
"Sketch files" .
The FileFilter class is defined in the javax.swing.filechooser package. Note that there is a
FileFilter interface defined in the java.io package that declares just one method, accept() ,
which is the same as the method in the FileFilter class. This interface is for use with the
listFiles() method that is defined in the File class, not for JFileChooser objects, so make sure
you don't confuse them. The filter object that you use with a file chooser must have the FileFilter
class as a superclass, and your filter class must define the getDescription() method as well as the
accept() method.
We can define our own file filter class for Sketcher as:
import javax.swing.filechooser.FileFilter;
import java.io.File;
public class ExtensionFilter extends FileFilter {
Search WWH ::




Custom Search