import java.awt.geom.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; import java.awt.print.*; public class PrintComponent extends JPanel implements Printable, ActionListener { final static Color bg = Color.white; final static JButton button = new JButton("Print"); public PrintComponent() { setBackground(bg); button.addActionListener(this); } public void actionPerformed(ActionEvent e) { //Now it is time to print. //First get a PrinterJob. PrinterJob printJob = PrinterJob.getPrinterJob(); //Then tell it what to print. printJob.setPrintable(this); //Show the print dialog. This is optional. if (printJob.printDialog()) { try { //User choosed to print, show the page dialog. //This is also optional. PageFormat pf = printJob.pageDialog(printJob.defaultPage()); //Set the new page format. printJob.validatePage(pf); //And finally start to print. printJob.print(); } catch (Exception ex) { ex.printStackTrace(); } } else //User did not want to print. System.out.println("User did not want to print"); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; drawShapes(g2); } public int print(Graphics g, PageFormat pf, int pageNo) throws PrinterException { if (pageNo >= 1) { return Printable.NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D)g; //The component on the screen does not have margains, //but the printed paper has. Move the graphics out of //the margains. g2.translate(pf.getImageableX(), pf.getImageableY()); //Paint exactly the same as in paintComponent. drawShapes(g2); return Printable.PAGE_EXISTS; } public void drawShapes(Graphics2D g2){ //Draw some graphics. g2.setColor(Color.black); g2.fill(new Rectangle2D.Float(20, 20, 80, 80)); g2.setColor(Color.gray); g2.fill(new Arc2D.Float(110, 100, 90, 50, 90, 170, Arc2D.PIE)); g2.setFont(new Font("Times New Roman", Font.BOLD, 40)); g2.drawString("Print me!!", 10, 290); } public static void main(String s[]){ JFrame f = new JFrame(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JPanel controlPanel = new JPanel(); controlPanel.add(button); f.getContentPane().add(BorderLayout.SOUTH, controlPanel); f.getContentPane().add(BorderLayout.CENTER, new PrintComponent()); f.setSize(300, 400); f.setVisible(true); } }