我是一个相对较新的程序员,所以这可能是一个非常简单的问题,但是让我有些困惑。
我正在尝试将Java GUI的最终输出打印到打印机。现在,在我的GUI中,有了它,当您单击打印时,会弹出一个弹出窗口,列出可用的打印机,并根据您选择的打印机,将其打印到该打印机。
但是事实并非如此。我通过搜索互联网来解决此问题,从而获得了大部分代码,并找到了一些很有前途的代码。但是,它是从文件打印出来的。因此,我在方法中所做的全部工作就是先将输出写入文件,以便可以使用相同的方法。
方法前的几件事:
没有引发任何错误或异常。
我每次尝试创建的文件始终存在,并且带有正确的文本。
我要打印的打印机正在接收打印作业,甚至认为它已经完成了。
如果我不得不猜测,我想我可能是将输出写入File的方式是打印机不会但不会告诉我。无论如何,这段代码中有很多地方我并不是很了解,所以请告诉我您可以找到什么。
这是我的代码:
private void printToPrinter() { File output = new File("PrintFile.txt"); output.setWritable(true); //Will become the user-selected printer. Object selection = null; try { BufferedWriter out = new BufferedWriter(new FileWriter(output)); out.write(calculationTextArea.getText() + "\n" + specificTextArea.getText()); out.close(); } catch (java.io.IOException e) { System.out.println("Unable to write Output to disk, error occured in saveToFile() Method."); } FileInputStream textStream = null; try { textStream = new FileInputStream("PrintFile.txt"); } catch (java.io.FileNotFoundException e) { System.out.println("Error trying to find the print file created in the printToPrinter() method"); } DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc mydoc = new SimpleDoc(textStream, flavor, null); //Look up available printers. PrintService[] printers = PrintServiceLookup.lookupPrintServices(flavor, null); if (printers.length == 0) { // No printers found. Inform user. jOptionPane2.showMessageDialog(this, "No printers could be found on your system!", "Error!", JOptionPane.ERROR_MESSAGE); } else { selection = jOptionPane2.showInputDialog(this, "Please select the desired printer:", "Print", JOptionPane.INFORMATION_MESSAGE, null, printers, PrintServiceLookup.lookupDefaultPrintService()); if (selection instanceof PrintService) { PrintService chosenPrinter = (PrintService) selection; DocPrintJob printJob = chosenPrinter.createPrintJob(); try { printJob.print(mydoc, null); } catch (javax.print.PrintException e) { jOptionPane2.showMessageDialog(this, "Unknown error occured while attempting to print.", "Error!", JOptionPane.ERROR_MESSAGE); } } } }
因此,我找到了一种最适合我的情况的方法,并且我认为我只发布它的内容,以防对任何人有用。
该解决方案的基础是Java确实拥有自己的完整版(至少与我的版本相比)printDialog popUp,它具有超出我所需的功能(页面布局编辑,预览等),使用它所需要做的就是一个实现Printable的对象,并且在该对象内您可以创建图形并绘制文档。
我只需要绘制我的输出String即可,而且很容易做到,我什至找到了StringReader,所以我可以天真地停止编写文件只是为了将我的输出保存在BufferedReader中。
这是代码。有两部分,方法和绘制图像的类:
方法:
private void printToPrinter() { String printData = CalculationTextArea.getText() + "\n" + SpecificTextArea.getText(); PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(new OutputPrinter(printData)); boolean doPrint = job.printDialog(); if (doPrint) { try { job.print(); } catch (PrinterException e) { // Print job did not complete. } } }
这是打印文档的类:
public class OutputPrinter implements Printable { private String printData; public OutputPrinter(String printDataIn) { this.printData = printDataIn; } @Override public int print(Graphics g, PageFormat pf, int page) throws PrinterException { // Should only have one page, and page # is zero-based. if (page > 0) { return NO_SUCH_PAGE; } // Adding the "Imageable" to the x and y puts the margins on the page. // To make it safe for printing. Graphics2D g2d = (Graphics2D)g; int x = (int) pf.getImageableX(); int y = (int) pf.getImageableY(); g2d.translate(x, y); // Calculate the line height Font font = new Font("Serif", Font.PLAIN, 10); FontMetrics metrics = g.getFontMetrics(font); int lineHeight = metrics.getHeight(); BufferedReader br = new BufferedReader(new StringReader(printData)); // Draw the page: try { String line; // Just a safety net in case no margin was added. x += 50; y += 50; while ((line = br.readLine()) != null) { y += lineHeight; g2d.drawString(line, x, y); } } catch (IOException e) { // } return PAGE_EXISTS; } }
无论如何,这就是我解决这个问题的方法!希望对某人有用!