The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: 2D Graphics
Lesson: Printing

## Printing the Contents of a Component

> Anything that you render to the screen can also be printed. You can easily use a Printable job to print the contents of a component.

### Example: ShapesPrint

> In this example we use the same rendering code to both display and print the contents of a component. When the user clicks the Print button, a print job is created, and `printDialog` is called to display the print dialog. If the user continues with the job, the printing process is initiated, and the printing system calls `print` as necessary to render the job to the printer.

> This figure has been reduced to fit on the page.
> Click the image to view it at its natural size.

> `ShapesPrint` is the page painter. Its `print` method calls `drawShapes` to perform the imaging for the print job. (The `drawShapes` method is also called by `paintComponent` to render to the screen.)

> >     public class ShapesPrint extends JPanel
> >                              implements Printable, ActionListener {
> >     ...
> >     public int print(Graphics g, PageFormat pf, int pi)
> >                               throws PrinterException {
> >         if (pi >= 1) {
> >             return Printable.NO_SUCH_PAGE;
> >         }
> >         drawShapes((Graphics2D) g);
> >         return Printable.PAGE_EXISTS;
> >     }
> >     ...
> >     public void drawShapes(Graphics2D g2) {
> >         Dimension d = getSize();
> >         int gridWidth = 400/6;
> >         int gridHeight = 300/2;
> >         int rowspacing = 5;
> >         int columnspacing = 7;
> >         int rectWidth = gridWidth - columnspacing;
> >         int rectHeight = gridHeight - rowspacing;
> >         ...

> >         int x = 85;
> >         int y = 87;
> >         ...
> >         g2.draw(new Rectangle2D.Double(x,y,rectWidth,rectHeight));
> >         ...

> The job control code is in the `ShapesPrint` `actionPerformed` method.

> >     public void actionPerformed(ActionEvent e) {
> >         if (e.getSource() instanceof JButton) {
> >             PrinterJob printJob = PrinterJob.getPrinterJob();
> >             printJob.setPrintable(this);
> >             if (printJob.printDialog()) {
> >                 try {
> >                     printJob.print();
> >                 } catch (Exception ex) {
> >                     ex.printStackTrace();
> >                 }
> >             }
> >         }
> >     }

> You can find the complete code for this program in `ShapesPrint.java`.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.