Java Reference
In-Depth Information
Example 12−1: ScribblePrinter1.java (continued)
this.printAll(g);
// Finish up.
g.dispose();
// End the current page
job.end();
// End the print job
}
/** Called when the user clicks to begin a scribble */
public void processMouseEvent(MouseEvent e) {
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
last_x = (short)e.getX();
// remember click position
last_y = (short)e.getY();
}
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) {
Graphics g = getGraphics();
g.drawLine(last_x, last_y, e.getX(), e.getY()); // draw the line
lines.addElement(new Line(last_x, last_y, // and save it
(short) e.getX(), (short)e.getY()));
last_x = (short) e.getX();
last_y = (short) e.getY();
}
else super.processMouseMotionEvent(e);
}
/** The main method. Create a ScribblePrinter1 object and away we go! */
public static void main(String[] args) {
Frame frame = new Frame("ScribblePrinter1");
ScribblePrinter1 s = new ScribblePrinter1(frame);
frame.add(s, BorderLayout.CENTER);
frame.setSize(400, 400);
frame.show();
}
/**
* This inner class stores the coordinates of one line of the scribble.
**/
class Line {
public short x1, y1, x2, y2;
public Line(short x1, short y1, short x2, short y2) {
this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
}
}
}
Printing with the Java 1.2 API
Example 12-2 does the same thing as Example 12-1 but has been modified to use
Swing, Java 2D, and the Java 1.2 Printing API. The Java 1.2 API is contained in the
java.awt.print package. Note that it uses the java.awt.print.PrinterJob class,
not the java.awt.PrintJob class of the Java 1.1 API. Our example class imple-
ments the java.awt.print.Printable interface, which means that it defines a
Search WWH ::




Custom Search