2010-08-12 67 views
0

如果您運行下面的代碼(從here),這兩個網頁叫了兩聲:Java打印中的重試次數?

class PrintObject implements Printable 
{ 
    public int print (Graphics g, PageFormat f, int pageIndex) 
    { 
     System.out.println("Page "+pageIndex); 
     Graphics2D g2 = (Graphics2D) g; // Allow use of Java 2 graphics on 
     // the print pages : 

     // A rectangle that shows the printable area of the page, allowing 
     // for margins all round. To be drawn on the first page (index = 0). 
     Rectangle2D rect = new Rectangle2D.Double(f.getImageableX(), 
     f.getImageableY(), 
     f.getImageableWidth(), 
     f.getImageableHeight()); 

     // A simple circle to go on the second page (index = 1). 
     Ellipse2D circle = new Ellipse2D.Double(100,100,100,100); 

     switch (pageIndex) 
     { 
      case 0 : g2.setColor(Color.black); // Page 1 : print a rectangle 
       g2.draw(rect); 
       return PAGE_EXISTS; 
      case 1 : g2.setColor(Color.red); // Page 2 : print a circle 
       g2.draw(circle); 
       return PAGE_EXISTS; 
      default: return NO_SUCH_PAGE; // No other pages 
     } 
    } 


    public static void main (String[] args) 
    { 
     // Create an object that will hold all print parameters, such as 
     // page size, printer resolution. In addition, it manages the print 
     // process (job). 
     PrinterJob job = PrinterJob.getPrinterJob(); 

     // It is first called to tell it what object will print each page. 
     job.setPrintable(new PrintObject()); 

     // Then it is called to display the standard print options dialog. 
     if (job.printDialog()) 
     { 
     // If the user has pressed OK (printDialog returns true), then go 
     // ahead with the printing. This is started by the simple call to 
     // the job print() method. When it runs, it calls the page print 
     // object for page index 0. Then page index 1, 2, and so on 
     // until NO_SUCH_PAGE is returned. 
     try { job.print(); } 
     catch (PrinterException e) { System.out.println(e); } 
     } 
    } 
} 

我不知道爲什麼會做這樣一個簡單的例子,但真正的問題是,我們有一些代碼打印一個大的JTable,並且在成功之前重試打印超過500次。即使是相對較小的JTable,也會重試11次。我們正在使用java.awt.print.PrintJob,關閉雙緩衝和使用CutePDF在具有2G RAM和1G堆(-Xmx1000m)的機器上測試

有誰知道會導致如此多的重試次數嗎?

+1

添加一些日誌記錄,看看它在做什麼。什麼聲明運行11次?每個變量看起來像那些11次?這看起來更像是調試請求,而不是關於打印的問題。 – bwawok 2010-08-12 22:27:02

+0

Basicaly我的問題是「是什麼導致java.awt.print.PrintJob做重試?」 – 2010-08-12 22:31:54

回答

0

我假設你正在討論每個頁面調用print(...)方法的頻率。

不幸的是,沒有真正的方法知道它將被調用多少次,更不用說控制它,因爲它是爲您的系統啓動JVM的打印子系統。

所有你能做的就是盡最大努力優化繪圖程序,知道它可以被多次調用(甚至過度)。

您應該也可以看看Graphic2D clipBounds,它可能會告訴您正在打印整個頁面的哪個子集。

在我的簡單測試中,在Mac上,使用您的代碼,打印每頁調用兩次。一旦使用了看起來像是用來獲取打印內容的圖形,然後再用實際系統Graphics2D來進行實際渲染,