|
|
Printing |
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.Example: ShapesPrint
In theShapesPrintexample, 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 andprintDialogis called to display the print dialog. If the user continues with the job, the printing process is initiated and the printing system callsShapesPrintis the page painter. ItsdrawShapesto perform the imaging for the print job. (ThedrawShapesmethod is also called bypaintComponentto render to the screen.)The job control code is in thepublic 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 w = d.width; int h = d.height; int x = w/3; int y = h/3; g2.setStroke(new BasicStroke(12.0f)); GradientPaint gp = new GradientPaint(x,y,Color.blue, x*2,y*2,Color.green); g2.setPaint(gp); g2.draw(new RoundRectangle2D.Double(x,y,x,y,10,10)); }ShapesPrintactionPerformedmethod:You can find the complete program inpublic void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj.equals(button)) { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(this); if (printJob.printDialog()) { try { printJob.print(); } catch (Exception ex) { ex.printStackTrace(); } } } }ShapesPrint.java.
|
|
Printing |