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

public class ComponentPrinterFrame
    extends JFrame
    implements Printable {
  public static void main(String[] args) {
    ComponentPrinterFrame cpf = new ComponentPrinterFrame();
    cpf.setVisible(true);
  }
  
  public ComponentPrinterFrame() {
    super("ComponentPrinterFrame v1.0");
    createUI();
  }
  
  protected void createUI() {
    JPanel panel = new JPanel();
    JButton printButton = new JButton("Print");
    panel.add(printButton);
    panel.add(new JList(new Object[] { "One", "Two", "Three" }));
    panel.add(new JButton("Push me"));
    panel.add(new JCheckBox("Chess", true));
    panel.add(new JComboBox(new Object[] { "Eins", "Zwei", "Drei" }));
    
    printButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        PrinterJob pj = PrinterJob.getPrinterJob();
        pj.setPrintable(ComponentPrinterFrame.this);
        if (pj.printDialog()) {
          try { pj.print(); }
          catch (PrinterException pe) {
            System.out.println(pe);
          }
        }
      }
    });

    setContentPane(panel);

    setSize(400, 400);
    // Center.
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = getSize();
    int x = (screenSize.width - frameSize.width) / 2;
    int y = (screenSize.height - frameSize.height) / 2;
    setLocation(x, y);
    
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        dispose();
        System.exit(0);
      }
    });
  }
  
  public int print(Graphics g, PageFormat pf, int pageIndex) {
    if (pageIndex != 0) return NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(pf.getImageableX(), pf.getImageableY());
    getContentPane().paint(g2);
    return PAGE_EXISTS;
  }
}

