Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Anything that you render to the screen can also be printed. You can easily use a Printable job to print the contents of a component.
In this example we use the same rendering code to both display and print the contents of a component. When the user clicks the Print button, a print job is created, andprintDialog
is called to display the print dialog. If the user continues with the job, the printing process is initiated, and the printing system calls
This figure has been reduced to fit on the page.
Click the image to view it at its natural size.
ShapesPrint
is the page painter. ItsdrawShapes
to perform the imaging for the print job. (ThedrawShapes
method is also called bypaintComponent
to render to the screen.)public class ShapesPrint extends JPanel implements Printable, ActionListener { ... public int print(Graphics g, PageFormat pf, int pi) throws PrinterException { if (pi >= 1) { return Printable.NO_SUCH_PAGE; } drawShapes((Graphics2D) g); return Printable.PAGE_EXISTS; } ... public void drawShapes(Graphics2D g2) { Dimension d = getSize(); int gridWidth = 400/6; int gridHeight = 300/2; int rowspacing = 5; int columnspacing = 7; int rectWidth = gridWidth - columnspacing; int rectHeight = gridHeight - rowspacing; ... int x = 85; int y = 87; ... g2.draw(new Rectangle2D.Double(x,y,rectWidth,rectHeight)); ...The job control code is in the
ShapesPrint
actionPerformed
method.public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(this); if (printJob.printDialog()) { try { printJob.print(); } catch (Exception ex) { ex.printStackTrace(); } } } }You can find the complete code for this program in
ShapesPrint.java
.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.