2017-11-18 186 views
0

好的。我正在嘗試爲Java練習做一個簡單的小文本編輯器。我在JavaFX 8中輸入文本的TextArea。我希望能夠創建並填充一個Text對象,然後將該文本對象發送給打印機。到目前爲止,我失敗了。打印機只是吐出一張白紙。它的行爲好像沒有內容需要打印。JavaFx轉換和打印

我發現那裏的文本對象被包裹在Java的TextFlow中像這樣的例子..

TextFlow printArea = new TextFlow(new Text(textDocument.getText())); 

至少打印出一些東西,但輸入的文字,這只是第一行。

這裏是我的打印代碼:

static void printOperation(TextArea textDocument) { 

    Text extractedText = new Text(textDocument.getText()); 
    PrinterJob printerJob = PrinterJob.createPrinterJob(); 

    if (printerJob != null && printerJob.showPageSetupDialog(textDocument.getScene().getWindow()) 
      && printerJob.showPrintDialog(textDocument.getScene().getWindow())) { 

     if (printerJob.printPage(extractedText)) { 
      printerJob.endJob(); 
     } else { 
      System.out.println("Failed to print"); 
     } 
    } else { 
     System.out.println("Canceled"); 
    } 
} 

//There is a print menu option that calls the print method 
     print.setOnAction((ActionEvent e) -> { 
      printOperation(textDocument); 
     }); 
+0

'job.printPage(textDocument );' – c0der

+0

謝謝,但我不想打印該節點。我按照說明使用節點的內容填充文本對象,然後打印該對象。 Text extractedText = new Text(textDocument.getText());由於某些原因,這不起作用。我必須做一些如何使該文本對象可打印。 –

+0

'job.printPage(textDocument);'工作嗎? – c0der

回答

0

Text通過似乎有它在不左上角一個節點的左下角原點。文字根本不在印刷區域內。

第二次嘗試可能無法達到所需的輸出,因爲您沒有對寬度設置任何限制。

通過使用StackPane作爲文本的父項,可以確保節點在屏幕上。此外,我建議您將wrappingWidth屬性:

static void printOperation(TextArea textDocument) { 
    Text extractedText = new Text(textDocument.getText()); 
    extractedText.setWrappingWidth(450); 

    // use pane to place the text 
    StackPane container = new StackPane(extractedText); 
    container.setAlignment(Pos.TOP_LEFT); 

    PrinterJob printerJob = PrinterJob.createPrinterJob(); 

    if (printerJob != null && printerJob.showPageSetupDialog(textDocument.getScene().getWindow()) 
      && printerJob.showPrintDialog(textDocument.getScene().getWindow())) { 

     if (printerJob.printPage(container)) { 
      printerJob.endJob(); 
     } else { 
      System.out.println("Failed to print"); 
     } 
    } else { 
     System.out.println("Canceled"); 
    } 
} 

您應根據用戶選擇的,而不是硬編碼,雖然值頁面大小/保證金可能設置wrappingWidth ...