Home : Course Map : Chapter 12 : Java :
Printing Java Interface Components
JavaTech
Course Map
Chapter 12

Printing
  Demo 1
Cursor Icons
  Demo 2
MouseButtons
  Demo 3
PopupMenu
  Demo 4
Keystrokes
  Demo 5
Audio
  Demo 6
Timing & Speed
  Demo 7
Toolkit
  Demo 8
AppletContext
  Demo 9
Exercises

    Supplements
Java Beans
More APIs
Java & Browsers
  Demo 1
     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

With Java 1.1 came the capability to print a copy of a Java frame. For version 1.2, Java2D API extended the printing capabilities with greater control over multiple page printing. (See the Java tutorial. for more info on Java 2D printing.)

Note: The printing system works with applications but the SecurityManager in the browser JVMs, however, will block printing from applets.

Printing here refers to painting to the printer instead of to the screen. In rendering Java components to the screen, we know that a Graphics context object comes as an argument in paint(Graphics g). for AWT components and also in the paintComponent(Graphics g) for Swing components. The graphics context methods then provide the methods for drawing and image display.

Similarly, for rendering to the printer, a PrintGraphics object, which is a subclass of Graphics, must be created and used instead of the usual Graphics object for monitor display..

PrintTestApp
(includes helper class PrintImagePanel)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

/**
  * This application illustrates printing in Java. The
  * frame displays an image.
 **/
public class PrintTestApp extends JFrame
             implements ActionListener
{

  PrintImagePanel fImgPanel;
  String fImageName = "dcx-flight.jpg";
  Image fImg;

  PrintTestApp (String name) {
    super (name);
  } // ctor

  /** Create the interface. **/
  public void init () {
    Container content_pane = getContentPane ();

    // Grab the image.
    fImg = getToolkit ().getImage (fImageName);

    // Create an instance of DrawingPanel
    fImgPanel = new PrintImagePanel (fImg);
    buildMenu (this);

    // Add the ImagePanel to the contentPane.
    content_pane.add (fImgPanel);
  }

  /** Create the "File" menu for the frame menu bar.**/
  void buildMenu (JFrame frame) {
    MenuBar mb = new MenuBar ();
    Menu m = new Menu ("File");

    MenuItem mi = new MenuItem ("Print");
    mi.addActionListener (this);
    m.add (mi);

    mi = new MenuItem ("Quit");
    mi.addActionListener (this);
    m.add (mi);

    mb.add (m);
    frame.setMenuBar (mb);
  } // init

  /** Execute the menu events here. **/
  public void actionPerformed (ActionEvent e) {
    String command = e.getActionCommand ();
    if (command.equals ("Quit")) {
        dispose ();
        System.exit (0);
    } else if (command.equals ("Print")) {
      print ();
    }
  } // actionPerformed

  /** Do the print setup up here. **/
  public void print () {
    // Create the PrintJob object
    PrintJob pjb = getToolkit ().getPrintJob (this,
         "Print Test", null);

    if (pjb != null) {
        Graphics pg = pjb.getGraphics ();
       if (pg != null) {
           paint (pg);// Paint all components on the frame
           pg.dispose (); // flush page
       }
       pjb.end (); // close print job
    }
  } // print

  /** Create a frame and add the applet to it.**/
  public static void main (String[] args) {
    //
    int frame_width  = 360;
    int frame_height = 360;

    PrintTestApp f = new PrintTestApp("Frame Print Demo");
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    f.init ();
    f.setSize (frame_width, frame_height);
    f.setVisible (true);
  } // main

} // class

/**
  * Draw an image on a JPanel. The constructor is passed
  * a reference to the image.
 **/
class PrintImagePanel extends JPanel
{
  Image fImg;

  /** Constructor is passed the image reference. **/
  PrintImagePanel (Image img) {
    fImg = img;
  } // ctor

  /** Paint the the image in the center of a blue background.**/
  public void paintComponent (Graphics g) {
    super.paintComponent (g);

    g.setFont (new Font ("Dialog", Font.BOLD, 12));
    String msg = "Print this window";

    int wd = getSize ().width;
    int ht = getSize ().height;

    int str_wd = g.getFontMetrics ().stringWidth (msg);
    int str_ht = g.getFontMetrics ().getHeight ();

    int x_str = (wd - str_wd)/2;
    int y_str = str_ht;

    g.drawString (msg, x_str, y_str);

    g.setColor (Color.blue);
    int img_wd = fImg.getWidth (this);
    int img_ht = fImg.getHeight (this);

    int x = (wd - img_wd)/2;
    int y = 2 * str_ht;

    g.fillRect (x-2, y-2, img_wd+4, img_ht+4);
    if (fImg != null) g.drawImage (fImg, x, y, this);

  } // paintComponent

} // PrintImagePanel

 

From the Component object you can obtain an access to the Toolkit, which provides various windowing services. Then from the Toolkit you can obtain a PrintJob object. In turn the PrintJob object provides a PrintGraphics object that is then passed to the paint() or paintComponent() method.

In the application PrintTestApp.java, a print dialog from the host system will appear to setup the printing as in this picture:

First the program invokes the method

  PrintJob getPrintJob(Frame frame, String title, Properties props)

from the AWT toolkit, which will bring up the system print dialog. The first argument in getPrintJob() references the frame to which the print dialog will belong. The title string, which will appear on the print dialog, comes second. Then the last argument is a reference to a properties object, which we set to null in the code in the above program. The properties were never standardized so they would will not be portable.

With Java 1.3 came a more elaborate method

  PrintJob getPrintJob(Frame f, String t, JobAttributes jA, PageAttributes pA)

in which references to instances of JobAttributes and PageAttributes class pass as arguments. These classes provide methods to set a wide range of printer control parameters such as the number of copies, the page ranges, paper size, orientation, and so forth.

The standard printable mode, uses the same format for the entire print out. A pageable mode allows for different formats for different pages. These pages can be combined in a Book object.

See the Printing in Java2D section of the Sun Java Tutorial for more about printing options. For example, your program can allow the user to open a Page Setup dialog to selection, for example, paper size and orientation .

Note:

  • As discussed in Chapter 6: Supplements: Java 2D Coordinates, for high resolution devices such as a printer, 72 user units in the drawing commands always gives 1 inch regardless of the dots-per-inch setting on the printer.

    Images will be printed according to their size settings rather than their pixel dimensions. That is, if a GIF file specifies the image as having pixel dimensions of 192 x 96 and a size of 2 inches x 1 inch (thus having a 96 DPI), it will be printed as 2 inches x 1 inch regardless of the printer's current DPI setting. (The printer control dialog, of course, may offer its own re-scaling options for the printed output.)

    This differs from the display on the monitor where the image will expand or contract according to the screen's resolution setting.

  • Components such as buttons, cam also paint themselves to the printer. This could be useful for saving a printout of the user interface for documentation purposes.

References & Web Resources

Latest update: Dec.6, 2004

              Tech
Tech APIs
Exercises

           Physics
Math/Science APIs
JAIDA Program
  Demo 1
Demo 1 Discussion
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.