Listing 6
120: /**
121: * Class: Document <p>
122: *
123: * This class is the painter for the document content. In this example,
124: * it will print an image of the NASA Space Station with a border around it.<p>
125: *
126: *
127: * @author Jean-Pierre Dube <jpdube@videotron.ca>
128: * @version 1.0
129: * @since 1.0
130: * @see Printable
131: */
132: private class Document extends Component implements Printable {
133:
134:
135: /**
136: * Method: print <p>
137: *
138: * @param g a value of type Graphics
139: * @param pageFormat a value of type PageFormat
140: * @param page a value of type int
141: * @return a value of type int
142: */
143: public int print (Graphics g, PageFormat pageFormat, int page) {
144:
145:
146: //--- Create the Graphics2D object
147: Graphics2D g2d = (Graphics2D) g;
148:
149: //--- Translate the origin to 0,0 for the top left corner
150: g2d.translate (pageFormat.getImageableX (), pageFormat.getImageableY ());
151:
152: //--- Set the drawing color to black
153: g2d.setPaint (Color.black);
154:
155: //--- Draw a border around the page using a 12 point border
156: g2d.setStroke (new BasicStroke (4));
157: Rectangle2D.Double border = new Rectangle2D.Double (0,
158: 0,
159: pageFormat.getImageableWidth (),
160: pageFormat.getImageableHeight ());
161:
162: g2d.draw (border);
163:
164:
165: //--- Create a media tracker and a URL object
166: MediaTracker mt = new MediaTracker (this);
167: URL imageURL = null;
168:
169: //--- Set the URL to the image that we want to load.
170: //--- NOTE: Change the path to reflect your location of the image.
171: //--- NOTE: Only the following image types are supported JPEG, GIF and PNG.
172: try {
173:
174: imageURL = new URL ("file:///c:/softdev/java/articles/javaworld/printing/part_2/ss2.jpg");
175: }
176: catch (MalformedURLException me) {
177: me.printStackTrace ();
178: }
179:
180: //--- Load the image and wait for it to load
181: Image image = Toolkit.getDefaultToolkit().getImage (imageURL);
182: mt.addImage (image, 0);
183: try {
184: mt.waitForID (0);
185: }
186: catch (InterruptedException e) {
187: }
188:
189: //--- Render the image on the sheet
190: g2d.drawImage (image,
191: (int) (0.25 * POINTS_PER_INCH),
192: (int) (0.25 * POINTS_PER_INCH),
193: (int) (8.5 * POINTS_PER_INCH),
194: (int) (6 * POINTS_PER_INCH),
195: this);
196:
197: //--- Validate the page
198: return (PAGE_EXISTS);
199: }
200: }
201:
202: } // Example6