Java Reference
In-Depth Information
Example 12−1: ScribblePrinter1.java (continued)
public class ScribblePrinter1 extends Panel {
private short last_x = 0, last_y = 0; // last click posistion
private Vector lines = new Vector(256,256); // store the scribble
private Properties printprefs = new Properties(); // store user preferences
private Frame frame;
public ScribblePrinter1(Frame frame) {
// Remember the frame: we'll need it to create a PrintJob
this.frame = frame;
// Register event types we're interested in for scribbling
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK);
// Add a print button to he layout, and respond to it by printing
Button b = new Button("Print");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { printScribble(); }
});
this.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
this.add(b);
}
/** Redraw (or print) the scribble based on stored lines */
public void paint(Graphics g) {
for(int i = 0; i < lines.size(); i++) {
Line l = (Line)lines.elementAt(i);
g.drawLine(l.x1, l.y1, l.x2, l.y2);
}
}
/** Print out the scribble */
public void printScribble() {
// Obtain a PrintJob
Toolkit toolkit = this.getToolkit();
PrintJob job = toolkit.getPrintJob(frame, "ScribblePrinter1", printprefs);
// If the user clicked Cancel in the print dialog, don't print
if (job == null) return;
// Get the Graphics object we use to draw to the printer
Graphics g = job.getGraphics();
// Give the output a larger top and left margin. Otherwise it will
// be scrunched up in the upper-left corner of the page.
g.translate(100, 100);
// Draw a border around the output area.
Dimension size = this.getSize();
g.drawRect(-1, -1, size.width+2, size.height+2);
// Set a clipping region so our scribbles don't go outside the border
// On-screen this happens automatically, but not on paper.
g.setClip(0, 0, size.width, size.height);
// Print this component and all components it contains
// This will invoke the paint() method, and will paint the button too.
// Use print() instead of printAll() if you don't the button to show.
Search WWH ::




Custom Search