2011-06-20 24 views
0

到目前爲止,這裏是我有:在單一的PrinterJob打印多JPanels

//標籤是一個JTabbedPane中

for(int i = 0; i < tab.getTabCount(); i ++){ 
     if(tab.getComponent(i) instanceof DuctReport) 
      PrintUtilities.printComponent(tab.getComponent(i), DuctReport.PRINT_SIZE); 
     else if(tab.getComponent(i) instanceof Vandy) 
      PrintUtilities.printComponent(tab.getComponent(i), Vandy.PRINT_SIZE); 
     else 
      PrintUtilities.printComponent(tab.getComponent(i), .8); 
    } 

//這裏是PrintUtilities代碼:

public class PrintUtilities implements Printable{ 

    private Component componentToBePrinted; 
    private double scale; 

    public static void printComponent(Component c,double scale) { 
     new PrintUtilities(c,scale).print(); 
    } 

    public PrintUtilities(Component componentToBePrinted, double scale) { 
     this.componentToBePrinted = componentToBePrinted; 
     this.scale = scale; 

    } 

    public void print() { 
     PrinterJob printJob = PrinterJob.getPrinterJob(); 
     printJob.setPrintable(this); 
     if (printJob.printDialog()) 
      try { 
       printJob.print(); 
      } catch(PrinterException pe) { 
       System.out.println("Error printing: " + pe); 
      } 
    } 

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) { 
     if (pageIndex > 0) { 
      return(NO_SUCH_PAGE); 
     } else { 
      Graphics2D g2d = (Graphics2D)g; 
      g2d.scale(scale, scale); 
      g2d.translate(pageFormat.getImageableX(),pageFormat.getImageableY()); 
      disableDoubleBuffering(componentToBePrinted); 
      componentToBePrinted.paint(g2d); 
      enableDoubleBuffering(componentToBePrinted); 
      return(PAGE_EXISTS); 
     } 
    } 

} 

當我做我有什麼,我必須單獨點擊「印刷」爲每個組件打印,任何想法我可以做什麼打印所有的組件在一個打印機上?

我還需要到中心頁面上的分量,我試圖做:

g2d.translate((pageFormat.getImageableWidth()-componentToBePrinted.getWidth)/2, 
       pageFormat.getImageableY()); 

,但在某些情況下,組件的寬度比成像寬度大,任何想法?

回答

0

嘗試增加每個JPanel的另一個JPanel中:

JPanel wrapper = new JPanel(); 

for(JPanel panel : yourPanels){ 
    wrapper.add(panel); 
} 

PrintUtilities.printComponent(wrapper, scale); 
+0

你的建議沒有奏效,只能打印第一張 –

+0

@Michael Rentmeister哦,我明白你要做什麼了。有一個打印機作業處理多個頁面的方式是通過Pageable。 http://download.oracle.com/javase/6/docs/api/java/awt/print/Pageable.html – Jeffrey

0

您可以將組件CON []作爲打印作業的參數,然後應用printutil遞歸相應

通在陣列中的所有面板和改變索引在print()函數中。