Java Reference
In-Depth Information
Clearly, using the
WindowAdapter
class as a base saves a lot of time and effort. Without it we would
have to define all seven of the methods declared in the interface in our class. Because our anonymous
class is an inner class its methods can access the fields of the
Sketcher
class, so the
windowClosing()
method we have defined can call our
checkForSave()
method for the
window
member of the
Sketcher
class object.
Now if you close the application window without having saved your sketch, you will be prompted to save it.
How It Works
This makes use of the code that we implemented for the save operation, packaged in the
checkForSave()
method. This does everything necessary to enable the sketch to be saved before the
application window is closed. Defining methods judiciously makes for economical coding.
This still leaves us with the now redundant
F
ile | Close
button to tidy up. As it's not really any different
from the
F
ile | New
function, let's change it to an application
Exit
button and reposition it at the
bottom of the
F
ile
menu. First, delete the statements that create the
closeAction
object and add it to
the
F
ile
menu. Next we can insert statements for an
else
if
block corresponding to the
closeAction
object event in the
actionPerformed()
method for the
FileAction
inner class to
SketchFrame
that will provide the close action functionality - checking to see whether the file should
be saved before exiting the program:
else if(name.equals(closeAction.getValue(NAME))) {
checkForSave();
System.exit(0);
}
Then we can redo the menu layout in the
Fi
le
menu constructor and add the mnemonic key
Ctrl-X
for
E
x
it
:
fileMenu.addSeparator(); // Add separator
addMenuItem(fileMenu, printAction);
fileMenu.addSeparator(); // Add separator
addMenuItem(fileMenu, closeAction = new FileAction("Exit",
KeyStroke.getKeyStroke('X',Event.CTRL
_
MASK ),
"Exit Sketcher"));
// We will add the types menu items here using actions...
All but one of our
F
ile
actions are now operable. To complete the set we just need to get print up
and running.
Printing in Java
Printing is always a messy business - inevitably so, because you have to worry about tedious details
such as the size of a page, the margin sizes, and how many pages you're going to need for your output.
As you might expect, the process for printing an image is different from printing text and you may also
have the added complication of several printers with different capabilities being available, so with
certain types of documents you need to select an appropriate printer. The way through this is to take it
one step at a time. Let's understand the general principles first.
There are five packages dedicated to supporting printing capabilities in Java. These are: