Printing Components

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

import java.awt.*;

public class PrintableFrame extends Frame 
 implements ActionListener {

  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 e) {

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

}

Previous | Next | Top
Last Modified April 19, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu