JMSL Chart Programmer's Guide
|
Actions >> Printing |
Printing
Printing from JFrameChart
The JFrameChart class, used to build most of the examples in this manual, includes a print option under the file menu. This option prints the chart as large as possible, without distortion, and centered on the page.
Printable Interface
The Java Printable interface is used to print a single page from Java. It is implemented by the class Chart. The following code fragment shows how to print a chart using its Printable interface and PrinterJob.
public void print() { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(chart); if (printJob.printDialog()) { try { printJob.print(); } catch (Exception ex) { ex.printStackTrace(); } } }
The PrinterJob.printDialog()
method displays a dialog box that may
contain a "Property Sheet." This property sheet is supplied by the hardware printer
driver, not by Java. User changes to property sheet values are not reflected back to
Java. Specifically, while a property sheet may allow the user to select landscape or
portrait mode, these settings are not reflected back to the PrinterJob object. The
correct way to set the orientation is by using the
PrinterJob.pageDialog(PageFormat)
method. For more details see
bug report 4311283 on Sun's Java site.
Pageable
The Java Pageable interface is used to print a complex document from Java. The
method Chart.paintChart(Graphics)
can be used to implement a Pageable
interface. The following method is the implementation of the Printable
interface in Chart. It uses the method Chart.paintChart(Graphics)
.
Note that the chart is drawn to fit the Component associated with the chart. The
getScreenSize
method returns the size of this component. The following
method scales the drawing to compensate for the difference in size between the
screen and the paper.
public int print(Graphics graphics, PageFormat pageFormat, int param) throws PrinterException { if (param >= 1) return Printable.NO_SUCH_PAGE; // translate, so we do not clip on the left // scale to fill the page graphics.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY()); // scale to fill the page double dw = pageFormat.getImageableWidth(); double dh = pageFormat.getImageableHeight(); Dimension screenSize = getScreenSize(); double xScale = dw / screenSize.width; double yScale = dh / screenSize.height; double scale = Math.min(xScale,yScale); // center the chart on the page double tx = 0.0; double ty = 0.0; if (xScale > scale) { tx = 0.5*(xScale-scale)*screenSize.width; } else { ty = 0.5*(yScale-scale)*screenSize.height; } ((Graphics2D)graphics).translate(tx, ty); ((Graphics2D)graphics).scale(scale, scale); Dimension bounds = new Dimension((int)dw,(int)dh); paint(new Draw(graphics,bounds)); return Printable.PAGE_EXISTS; }
© Visual Numerics, Inc. All rights reserved. |