Prints the component - Java 2D Graphics

Java examples for 2D Graphics:Print

Description

Prints the component

Demo Code


import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.RepaintManager;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.awt.print.PrinterException;
import java.awt.print.PageFormat;

public class Main{
    private Component componentToBePrinted;

    /**//from  w  w w  . j  av  a  2 s  . c o m
    The print dialog.
     */
    public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        // print if user does not cancel
        if (printJob.printDialog())
            try {
                printJob.print();
            } catch (PrinterException pe) {
                System.out.println("Error printing: " + pe);
            }
    }
    /**
    Prints the page at the specified index into the specified Graphics context in the specified format.
     */
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        // checks if page exist
        if (pageIndex > 0) {
            return (NO_SUCH_PAGE);
        } else {
            Graphics2D g2d = (Graphics2D) g;
            g2d.translate(pageFormat.getImageableX(),
                    pageFormat.getImageableY());
            disableDoubleBuffering(componentToBePrinted);
            componentToBePrinted.paint(g2d);
            enableDoubleBuffering(componentToBePrinted);
            return (PAGE_EXISTS);
        }
    }
    /**
    Disables double buffering.
     */
    public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
    }
    /**
    Enables double buffering.
     */
    public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }
}

Related Tutorials