|
|
|
|
Print Preview
Below is a print preview example using the MaiArch.Infrastructure.PrintPreview component.
You can download the PrintPreview.jar file from PrintPreview.jar download
With this class you have to implement the printable method, sending the print stuff to the PrintPreview print method.
This allows multi page swing components to be printed. The PrintPreview class produces an image of the components
and then returns this in a JPanel. You can then pop this wherever you want ( in the example below in a simple JFrame ).
package examples;
import MaiArch.Infrastructure.PrintPreview;
import javax.swing.JLabel; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.print.Printable; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.awt.Graphics;
public class PrintExample extends JPanel implements Printable{
public PrintExample() { initLayout(); } /** * put a load of labels on this panel to that it is more than 1 page long. */ void initLayout() { setLayout(new GridLayout(50,2)); for(int i=0; i < 100; i++) { JLabel lbl = new JLabel("Label " + i); lbl.setPreferredSize(new Dimension(100,25)); add(lbl); } }
/** * Copy this code to override the print method of any multi page and make the panel * both printable and previewable */ PrintPreview pp = null; public int print(Graphics g, PageFormat pf, int pageNumber) throws PrinterException { if(pp == null) pp = new PrintPreview(this); return pp.print(g, pf, pageNumber); } /** * * @param arg * */ public static void main(String arg[]) { PrintExample printExample = new PrintExample(); // create the panel showComponent(printExample); //display the component in a JFrame showPrintPreview(printExample); //preview the panel printComponent((Printable)printExample); //print the panel } static Component showComponent(Component componentPanel) { //create a panel and show in a frame. JFrame fcomponent = new JFrame("Component frame"); fcomponent.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fcomponent.add(new JScrollPane(componentPanel)); fcomponent.pack(); fcomponent.show(); return componentPanel; } static void showPrintPreview(Component c) { //gerate a new panel which is a print preview of the component pagel PrintPreview pp = new PrintPreview(c); JFrame fpreview = new JFrame("print preview frame ( component as image) "); try{ fpreview.add(new JScrollPane(pp.previewComponent())); } catch(Exception e){ System.out.print("exception:" + e.getMessage());} fpreview.pack(); fpreview.show(); fpreview.setLocation(300,0); } static void printComponent(Printable printable) { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(printable); if(printJob.printDialog()){ try { printJob.print(); } catch (Exception e) {System.out.print("exception:" + e.getMessage());} } } }
|