Printing Components

Printing Components

How do I print out a component?

Java 1.1 introduced the java.awt.PrintJob and java.awt.PrintGraphicsclasses. It also added the print(Graphics) and printAll(Graphics)methods to java.awt.Component, and the printComponents(Graphics) methodto java.awt.Container. To print a component, you really ony need toconcern yourself with the PrintJob class and the print(Graphics)method in Component.

The procedure for printing a component is to create a PrintJob instance,obtain its drawing context through getGraphics(), use that as an argumentto print(Graphics), and end the print job by calling the PrintJob end()method. The only tricky part of this procedure is to create a PrintJobinstance. You do not use the new operator to do that. Rather, youget the default Toolkit instance, using Toolkit.getDefaultToolkit(),and then create a PrintJob through getPrintJob(Frame, String, Properties).The Toolkit class mediates between the pure Java environment and thesystem dependent facilities.

Below is an example of a button that prints itself. Note that you shouldcall print(), and not printComponents(). Also, on most systems,getPrintJob() will block, presenting the user with a print configurationdialog. If the user dismisses the dialog by pressing the cancel button,getPrintJob() will return null, which is why you should check the returnvalue before using it.

import java.awt.*;import java.awt.event.*;import*;public final class Print {  public static final void main(String[] args) {    WindowListener exitListener;    final JFrame frame = new JFrame();    final JButton button = new JButton("Print");    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window;        window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }    };                                   button.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent e) {	if(e.getSource() == button) {	  PrintJob job;	  Graphics g;	  job = Toolkit.getDefaultToolkit().getPrintJob(frame, "A Print Job",							null);	  if(job == null) {	    JOptionPane pane;	    JOptionPane.showMessageDialog(frame, "Could not get print job!",					  "Error", JOptionPane.ERROR_MESSAGE); 	    return;	  }	  g = job.getGraphics();	  frame.print(g);	  job.end();	}      }    });    frame.getContentPane().add(button);    frame.addWindowListener(exitListener);    frame.pack();;  }}
See also  Comparing different methods of testing your Infrastructure-as-Code

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist