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 theShapesPrint
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 callsShapesPrint
is the page painter. ItsdrawShapes
to perform the imaging for the print job. (ThedrawShapes
method is also called bypaintComponent
to 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)); }ShapesPrint
actionPerformed
method: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 |