Download the JDK
Search the Tutorials
Hide the TOC
Trail: 2D Graphics
Lesson: Printing
Printing
A Basic Printing Program
Using Print Setup Dialogs
Printing a Multiple Page Document
Working with Print Services and Attributes
Printing the Contents of a User Interface
Printing Support in Swing Components
Home Page > 2D Graphics > Printing
Printing the Contents of a User Interface

> Another common printing task is to print the contents of a window or a frame, either in whole, or in part. The window may contain the following components: toolbars, buttons sliders, text labels, scrollable text areas, images, and other graphical content. All of these components are printed using the following methods of the Java 2D™ printing API:

>     java.awt.Component.print(Graphics g);
>     java.awt.Component.printAll(Graphics g);

> The following figure represents a simple user interface.

> The code to create this UI is located in the sample program `PrintUIWindow.java`.

> To print this window, modify the code in the earlier examples which printed text or images. The resulting code should appear as follows:

>        public int print(Graphics g, PageFormat pf, int page) throws
>                                                         PrinterException {
>             if (page > 0) {
>                 return NO_SUCH_PAGE;
>             }

>             Graphics2D g2d = (Graphics2D)g;
>             g2d.translate(pf.getImageableX(), pf.getImageableY());

>             /* Print the entire visible contents of a java.awt.Frame */
>             frame.printAll(g);

>             return PAGE_EXISTS;
>         }

>     Note: The call to the printAll method is the only difference between
>     this example and examples to print text or image.
>     The print(Graphics g) method mirrors the java.awt.Component.paint(Graphics g) method used
>     for on-screen rendering. Use the print() method rather
>     than the paint() method as the Components class may have overridden the
>     print() method to handle the printing case differently.

>     The printAll(Graphics g)method prints the component and
>     all its subcomponents. This method is usually used to print
>     object such as a complete window, rather than a single component.

Previous page: Working with Print Services and Attributes
Next page: Printing Support in Swing Components