Java Reference
In-Depth Information
Example 12−2: ScribblePrinter2.java (continued)
// Finally, print the component by calling the paintComponent() method.
// Or, call paint() to paint the component, its background, border, and
// children, including the Print JButton
this.paintComponent(g);
// Tell the PrinterJob that the page number was valid
return Printable.PAGE_EXISTS;
}
/** Called when the user clicks to begin a scribble */
public void processMouseEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
scribble.moveTo(e.getX(), e.getY()); // Start a new line
}
else super.processMouseEvent(e);
}
/** Called when the the user drags the mouse: does the scribbling */
public void processMouseMotionEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_DRAGGED) {
scribble.lineTo(e.getX(), e.getY()); // Add a line to the scribble
repaint(); // Redraw the whole scribble. Clean but a little slow
}
else super.processMouseMotionEvent(e);
}
/** The main method. Create a ScribblePrinter2 object and away we go! */
public static void main(String[] args) {
JFrame frame = new JFrame("ScribblePrinter2");
ScribblePrinter2 s = new ScribblePrinter2();
frame.getContentPane().add(s, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Printing Multipage Text Documents
The two printing examples we've seen so far print GUI components on a single
page. Printing multipage documents is more interesting, but also trickier, because
we have to decide where to place the page breaks. Example 12-3 shows how this
can be done. This HardcopyWriter class is a custom java.io.Writer stream that
uses the Java 1.1 Printing API to print the characters sent through it, inserting line
breaks and page breaks as necessary.
The HardcopyWriter class includes two demonstration programs as inner classes.
The first, PrintFile , reads a specified text file and prints it by sending its contents
to a HardcopyWriter stream. The second, Demo , prints a demonstration page that
shows off the font and tabbing capabilities of the class, as shown in Figure 12-1.
Example 12-3 is long but worth studying. In addition to demonstrating the Java 1.1
Printing API again, it shows an approach to paginating a text document. It is also a
useful example of a custom Writer stream.
Search WWH ::




Custom Search