Java Reference
In-Depth Information
print() method that allows it to be printed by a PrinterJob . printScribble()
starts things off by obtaining a PrinterJob object and telling it what to print, and
the print() method does the rest. Like the previous example, this one uses the
component's own drawing method, paintComponent() in this case, to do the
actual printing. You can find another example of the Java 1.2 Printing API in
Example 11-18.
Example 12−2: ScribblePrinter2.java
package com.davidflanagan.examples.print;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
/**
* A "scribble" application that remembers the scribble and allows the user
* to print it. It displays a Swing API and uses the Java 1.2 printing API.
* It also uses Java2D features to draw and represent the scribble.
**/
public class ScribblePrinter2 extends JComponent implements Printable {
Stroke linestyle = new BasicStroke(3.0f); // Draw with wide lines
GeneralPath scribble = new GeneralPath(); // Holds the scribble
public ScribblePrinter2() {
// 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
JButton b = new JButton("Print");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { printScribble(); }
});
this.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
this.add(b);
}
/** Redraw (or print) the scribble based on stored lines */
public void paintComponent(Graphics g) {
super.paintComponent(g); // Allow the superclass to draw itself
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(linestyle); // Specify wide lines
g2.draw(scribble);
// Draw the scribble
}
/**
* Print out the scribble. This is the method invoked by the Print button;
* it is not part of the Printable interface
**/
public void printScribble() {
// Obtain a java.awt.print.PrinterJob (not java.awt.PrintJob)
PrinterJob job = PrinterJob.getPrinterJob();
// Tell the PrinterJob to print us (since we implement Printable)
// using the default page layout
job.setPrintable(this, job.defaultPage());
Search WWH ::




Custom Search