Java Formatter receipt printing issue

Lawrence Wong picture Lawrence Wong · Nov 7, 2014 · Viewed 8.4k times · Source

I am designing a receipt to print out in Java using the PrinterJob class.

I need some advice.

Based on the example I saw here.

http://www.javadocexamples.com/java_source/__/re/Receipt.java.html

How do I store the output given in the example above in a jTextPanel? I will then print out the text content inside the jTextPanel using the PrinterJob class.

I want to get the following output when I print out the text content inside the jTextPanel from my POS printer.

enter image description here

Below are the codes I have so far.

String s = String.format("Item Qty Price", "%-15s %5s %10s\n");
        String s1 = String.format("---- --- -----","%-15s %5s %10s\n");
        String output = s + s1;

        jTextPane1.setText(output);

        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat pageFormat = printerJob.defaultPage();
        Paper paper = new Paper();
        paper.setSize(180.0, (double) (paper.getHeight() + lines * 10.0));
        paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight() - margin * 2);
        pageFormat.setPaper(paper);
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        printerJob.setPrintable(jTextPane1.getPrintable(null, null), pageFormat);
        printerJob.print();

Any advice on how can I proceed?

Answer

Erwin Bolwidt picture Erwin Bolwidt · Nov 7, 2014

The order in which you pass arguments to String.format is wrong. The format string goes first (the one with the percentage signs), and then you pass multiple arguments, one argument for each percent in the format string.

So in your case:

String s = String.format("%-15s %5s %10s\n", "Item", "Qty", "Price");
String s1 = String.format("%-15s %5s %10s\n", "----", "---", "-----");

You also need a format string for the line items. From your output, that could be:

"%-15s %5d %10.2f\n"

(Which you would use as:

String line = String.format("%-15s %5d %10.2f\n", itemName, quantity, price);

)

If you want to truncate your itemName if it's longer than 15 characters, you can use:

// "%.15s %5d %10.2f\n"
String line = String.format("%.15s %5d %10.2f\n", itemName, quantity, price);