2011-06-02 50 views
9

我剛剛開始to learn how to print a window in Java/Swing。 (編輯:剛發現the Java Printing Guidejava:爲打印對話框設置頁面範圍

當我這樣做:

protected void doPrint() { 
    PrinterJob job = PrinterJob.getPrinterJob(); 
    job.setPrintable(this); 
    boolean ok = job.printDialog(); 
    if (ok) { 
     try { 
      job.print(); 
     } 
     catch (PrinterException ex) { 
      ex.printStackTrace(); 
     } 
     finally { 

     } 
    } 
} 

我得到這個打印機對話框(在Windows XP):

enter image description here

如何改變頁面所以它不是1-9999?

編輯:使用Pageable/Book設置頁面範圍(如@t_barbz有益指出)需要PageFormat,在這種情況下,我有一個catch-22,因爲我想在打印對話框選擇,和我似乎沒有從打印對話框中獲得返回值。

+5

我認爲,「NT」在「打印」的結束,但由於某種原因,你的圖標將其覆蓋。 – 2011-06-02 15:26:19

+0

它不是* my *圖標,它是標準的Java圖標。 – 2011-06-02 15:31:36

+0

@Abdullah - OH!我只是從另一個應用程序做了一個打印,那裏沒有圖標。 – 2011-06-02 15:32:15

回答

4

對於頁面範圍我相信你需要使用PrinterJob的setPageable(Pageable document)方法。看起來它應該做的伎倆。

protected void doPrint() { 
PrinterJob job = PrinterJob.getPrinterJob(); 
Book book = new Book(); 
book.append(this, job.defaultPage()); 
printJob.setPageable(book); 

boolean ok = job.printDialog(); 
if (ok) { 
    try { 
     job.print(); 
    } 
    catch (PrinterException ex) { 
     ex.printStackTrace(); 
    } 
    finally { 

    } 
} 
} 
+0

嗯。不那麼容易。雖然'Pageable'可以讓你返回頁面數量,但它也需要你提供一個PageFormat文檔,我不知道該怎麼做。 – 2011-06-02 15:36:49

+0

阿哈 - 你的編輯幫助。謝謝! – 2011-06-02 15:40:01

+0

book.append(可打印)需要一個PageFormat,它不能爲null,所以我回到了原點。 – 2011-06-02 15:41:46

1

最後這裏是一個簡單的代碼:

PrinterJob job = PrinterJob.getPrinterJob(); 
job.setPrintable(this); 
PrintRequestAttributeSet printAttribute = new HashPrintRequestAttributeSet(); 
printAttribute.add(new PageRanges(1, 100));   
boolean ok = job.printDialog(printAttribute); 
if (ok) { 
    try { 
      job.print(); 
    } catch (PrinterException ex) { 
     /* The job did not successfully complete */ 
    } 
}