Printing Components

The following simple program prints itself when you press the print button:

import java.awt.*;

public class PrintableFrame extends Frame 
 implements ActionListener {

  private Button printButton;

  public static void main(String[] args) {

    PrintableFrame pf = new PrintableFrame("Printable Frame");
    Label quote = new Label(
     "Now is the time for all good men to come to the aid of their country.");
    pf.add("North", quote);

  }
  
  public PrintableFrame(String s) {
    super(s);
    setSize(350, 200);
    setLocation(100, 100);
    printButton = new Button("Print Me!");
    printButton.addActionListener(this);
    Panel p = new Panel();
    p.add(printButton);
    add("South", p);
  }
  
  public void actionPerformed(ActionEvent evt) {

    PrintJob pj = getToolkit().getPrintJob(this, getTitle(), null);
    if (pj != null) {
      Graphics pg = pj.getGraphics();
      printComponents(pg);
      pg.dispose();
      pj.end();
    }
    
  }

}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 26, 2006