FileDocCategorySizeDatePackage
PrintableComponent.javaAPI DocExample2516Mon Oct 11 15:07:22 BST 1999None

PrintableComponent

public class PrintableComponent extends Object implements Printable
This wrapper class encapsulates a Component and allows it to be printed using the Java 2 printing API.

Fields Summary
Component
c
Constructors Summary
public PrintableComponent(Component c)
Create a PrintableComponent wrapper around a Component

 this.c = c; 
Methods Summary
public voidprint()
This method is not part of the Printable interface. It is a method that sets up the PrinterJob and initiates the printing.

    // Get the PrinterJob object
    PrinterJob job = PrinterJob.getPrinterJob();
    // Get the default page format, then allow the user to modify it
    PageFormat format = job.pageDialog(job.defaultPage());
    // Tell the PrinterJob what to print
    job.setPrintable(this, format);
    // Ask the user to confirm, and then begin the printing process
    if (job.printDialog()) 
      job.print();
  
public intprint(java.awt.Graphics g, java.awt.print.PageFormat format, int pagenum)
This is the "callback" method that the PrinterJob will invoke. This method is defined by the Printable interface.

    // The PrinterJob will keep trying to print pages until we return
    // this value to tell it that it has reached the end.
    if (pagenum > 0) 
      return Printable.NO_SUCH_PAGE;

    // We're passed a Graphics object, but it can always be cast to Graphics2D
    Graphics2D g2 = (Graphics2D) g;

    // Use the top and left margins specified in the PageFormat Note
    // that the PageFormat methods are poorly named.  They specify
    // margins, not the actual imageable area of the printer.
    g2.translate(format.getImageableX(), format.getImageableY());

    // Tell the component to draw itself to the printer by passing in 
    // the Graphics2D object.  This will not work well if the component
    // has double-buffering enabled.
    c.paint(g2);

    // Return this constant to tell the PrinterJob that we printed the page.
    return Printable.PAGE_EXISTS;