The popup menu visible in Example 8.1 shows that that example application supports a Print command. One of the most exciting new features of Java 1.1 is the ability of programs to generate hardcopy. You draw on a page in Java just as you draw on the screen: by invoking methods of a Graphics object. The difference, of course, is in the Graphics object. When drawing to the screen, you are given an instance of one subclass of Graphics, and when printing, you are given an instance of some other subclass. The two subclasses implement the necessary functionality for on-screen drawing and printing, respectively.
To print in Java 1.1, follow these steps:
Printing AWT components and hierarchies of components is particularly easy. You simply pass a print Graphics object to the print() method of the component you want to print. By default, print() simply passes this Graphics object to the paint() method. If a component wants to display itself differently on paper than it does on screen, however, it might implement a custom print() method. To print a complete hierarchy of components, you simply call the printAll() method of the root component of the hierarchy.
An important restriction on printing is that applets cannot initiate print jobs. This does not mean that they cannot define custom print() methods to allow themselves to be printed; merely that the Web browser or applet viewer must initiate the print job, and invoke the printAll() method of the applet.
The print() method of Example 8.1 shows how to generate hardcopy. Note that this Scribble.print() method happens to have the same name as the Component.print() method discussed above. The two methods have different arguments, however, so Scribble.print() does not override Component.print().