01: /*
02: * Created on 02-Oct-2003
03: */
04: package uk.org.ponder.swingutil;
05:
06: import java.awt.*;
07: import javax.swing.*;
08: import java.awt.print.*;
09:
10: // written by Marty Hall, Applied Physics Lab, Johns Hopkins University.
11: // http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html
12:
13: /** A class automating the printing of the complete contents of a SWING component, including
14: * scaling optimally to fill a page.
15: * All that is required is a simple call to the printComponent() method.
16: * Why didn't SUN supply this?
17: *
18: * @author Bosmon
19: */
20: public class PrintUtilities implements Printable {
21: private Component componentToBePrinted;
22:
23: /** Opens a print dialog to the user allowing the printing of the specified component.
24: * @param c The component to be printed.
25: */
26: public static void printComponent(Component c) {
27: new PrintUtilities(c).print();
28: }
29:
30: public PrintUtilities(Component componentToBePrinted) {
31: this .componentToBePrinted = componentToBePrinted;
32: }
33:
34: public void print() {
35: PrinterJob printJob = PrinterJob.getPrinterJob();
36: printJob.setPrintable(this );
37: if (printJob.printDialog())
38: try {
39: printJob.print();
40: } catch (PrinterException pe) {
41: System.out.println("Error printing: " + pe);
42: }
43: }
44:
45: public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
46: if (pageIndex > 0) {
47: return (NO_SUCH_PAGE);
48: } else {
49: Graphics2D g2d = (Graphics2D) g;
50: scalePage(g2d, pageFormat);
51: disableDoubleBuffering(componentToBePrinted);
52: componentToBePrinted.paint(g2d);
53: enableDoubleBuffering(componentToBePrinted);
54: return (PAGE_EXISTS);
55: }
56: }
57:
58: private void scalePage(Graphics2D g2, PageFormat pageformat) {
59: Rectangle componentBounds = this .componentToBePrinted
60: .getBounds(null);
61: double scaleX = pageformat.getImageableWidth()
62: / componentBounds.width;
63: double scaleY = pageformat.getImageableHeight()
64: / componentBounds.height;
65: System.out.println("Scale: " + scaleX + " " + scaleY);
66: if (scaleX < 1 || scaleY < 1) {
67: if (scaleX < scaleY) {
68: scaleY = scaleX;
69: } else {
70: scaleX = scaleY;
71: }
72: g2.translate(pageformat.getImageableX(), pageformat
73: .getImageableY());
74: g2.scale(scaleX, scaleY);
75: }
76:
77: }
78:
79: public static void disableDoubleBuffering(Component c) {
80: RepaintManager currentManager = RepaintManager
81: .currentManager(c);
82: currentManager.setDoubleBufferingEnabled(false);
83: }
84:
85: public static void enableDoubleBuffering(Component c) {
86: RepaintManager currentManager = RepaintManager
87: .currentManager(c);
88: currentManager.setDoubleBufferingEnabled(true);
89: }
90: }
|