3

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?

Lawrence Wong
  • 1,129
  • 4
  • 24
  • 40

1 Answers1

5

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);
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
  • How to handle cases where the item name is very long? – Vivek Maskara Feb 19 '18 at 13:51
  • I added the solution for that to the answer. – Erwin Bolwidt Feb 19 '18 at 14:39
  • how do i wrap long itemName to multiple lines? – Smith Jul 03 '19 at 22:02
  • @Smith You'll need to then spit up the itemName yourself in a for-loop; every line except for the last only has a 15-character itemName portion, and the last one has the quantity and the price too. But if you want to line-wrap nicely you'll need to do it at word boundaries, except if the word is already longer than 15 characters. – Erwin Bolwidt Jul 04 '19 at 00:34