Listing 1
1:
2: /**
3: * Class: Example1 <p>
4: *
5: * @author Jean-Pierre Dube <jpdube@videotron.ca>
6: * @version 1.0
7: * @since 1.0
8: * @see Printable
9: */
10:
11: import java.awt.*;
12: import java.awt.geom.*;
13: import java.awt.print.*;
14:
15:
16: public class Example1 implements Printable {
17:
18: //--- Private instances declarations
19: private final double INCH = 72;
20:
21:
22:
23: /**
24: * Constructor: Example1 <p>
25: *
26: */
27: public Example1 () {
28:
29: //--- Create a printerJob object
30: PrinterJob printJob = PrinterJob.getPrinterJob ();
31:
32: //--- Set the printable class to this one since we
33: //--- are implementing the Printable interface
34: printJob.setPrintable (this);
35:
36: //--- Show a print dialog to the user. If the user
37: //--- clicks the print button, then print, otherwise
38: //--- cancel the print job
39: if (printJob.printDialog()) {
40: try {
41: printJob.print();
42: } catch (Exception PrintException) {
43: PrintException.printStackTrace();
44: }
45: }
46:
47: }
48:
49:
50: /**
51: * Method: print <p>
52: *
53: * This class is responsible for rendering a page using
54: * the provided parameters. The result will be a grid
55: * where each cell will be half an inch by half an inch.
56: *
57: * @param g a value of type Graphics
58: * @param pageFormat a value of type PageFormat
59: * @param page a value of type int
60: * @return a value of type int
61: */
62: public int print (Graphics g, PageFormat pageFormat, int page) {
63:
64: int i;
65: Graphics2D g2d;
66: Line2D.Double line = new Line2D.Double ();
67:
68: //--- Validate the page number, we only print the first page
69: if (page == 0) {
70:
71: //--- Create a graphic2D object and set the default parameters
72: g2d = (Graphics2D) g;
73: g2d.setColor (Color.black);
74:
75: //--- Translate the origin to be (0,0)
76: g2d.translate (pageFormat.getImageableX (), pageFormat.getImageableY ());
77:
78: //--- Print the vertical lines
79: for (i = 0; i < pageFormat.getWidth (); i += INCH / 2) {
80: line.setLine (i, 0, i, pageFormat.getHeight ());
81: g2d.draw (line);
82: }
83:
84: //--- Print the horizontal lines
85: for (i = 0; i < pageFormat.getHeight (); i += INCH / 2) {
86: line.setLine (0, i, pageFormat.getWidth (), i);
87: g2d.draw (line);
88: }
89:
90: return (PAGE_EXISTS);
91: }
92: else
93: return (NO_SUCH_PAGE);
94: }
95:
96: } //Example1