Previous | Next | Trail Map | 2D Graphics | 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 the ShapesPrint 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.

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 w = d.width;
    int h = d.height;
    int x = w/3;
    int y = h/3;
    g2.setStroke(new BasicStroke(12.0f));
    GradientPaint gp = new GradientPaint(x,y,Color.blue,
                                         x*2,y*2,Color.green);
    g2.setPaint(gp);
    g2.draw(new RoundRectangle2D.Double(x,y,x,y,10,10));
}
The job control code is in the ShapesPrint actionPerformed method:

public void actionPerformed(ActionEvent e) {
    Object obj = e.getSource();
    if (obj.equals(button)) {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog()) {
            try {
                printJob.print();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
You can find the complete program in ShapesPrint.java.


Previous | Next | Trail Map | 2D Graphics | Printing